diff --git a/cmd/grus/main.go b/cmd/grus/main.go index de77d25..a97fd3c 100644 --- a/cmd/grus/main.go +++ b/cmd/grus/main.go @@ -1,35 +1,77 @@ -// Command grus is the Grus controller binary. Subcommands: controller, fetch, openapi, version. +// Command grus is the Grus controller and command line client. +// Server side subcommands: controller, fetch, openapi, version. The client commands live in internal/cli. package main import ( + "context" "fmt" "os" + "os/signal" + "syscall" + + "github.com/spf13/cobra" + + "github.com/OneLiteFeatherNET/grus/internal/cli" ) // version is set at build time with -ldflags "-X main.version=...". var version = "dev" func main() { - if len(os.Args) < 2 { - fmt.Fprintln(os.Stderr, "usage: grus [flags]") - os.Exit(2) - } - var err error - switch os.Args[1] { - case "controller": - err = runController(os.Args[2:]) - case "fetch": - err = runFetch(os.Args[2:]) - case "openapi": - err = runOpenAPI() - case "version": - fmt.Println(version) - default: - fmt.Fprintf(os.Stderr, "unknown subcommand %q\n", os.Args[1]) - os.Exit(2) - } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + root := newRootCmd() + cmd, err := root.ExecuteContextC(ctx) + stop() if err != nil { - fmt.Fprintf(os.Stderr, "grus %s: %v\n", os.Args[1], err) + name := "grus" + if cmd != nil { + name = cmd.CommandPath() + } + fmt.Fprintf(os.Stderr, "%s: %v\n", name, err) os.Exit(1) } } + +// newRootCmd assembles the client commands and the server side subcommands. +func newRootCmd() *cobra.Command { + root := cli.NewRoot(&cli.Env{}) + root.AddCommand(controllerCmd(), fetchCmd(), openapiCmd(), versionCmd()) + return root +} + +// passthrough leaves flag parsing to the command's own flag set, so `controller` and `fetch` keep +// exactly their former flags and error messages. +func passthrough(use, short string, run func(args []string) error) *cobra.Command { + return &cobra.Command{ + Use: use, + Short: short, + DisableFlagParsing: true, + RunE: func(_ *cobra.Command, args []string) error { return run(args) }, + } +} + +func controllerCmd() *cobra.Command { + return passthrough("controller [flags]", "Run the controller", runController) +} + +func fetchCmd() *cobra.Command { + return passthrough("fetch --dest ", "Download the templates named in GRUS_FETCH_TEMPLATES (init container)", runFetch) +} + +func openapiCmd() *cobra.Command { + return &cobra.Command{ + Use: "openapi", + Short: "Print the OpenAPI document", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { return runOpenAPI(cmd.OutOrStdout()) }, + } +} + +func versionCmd() *cobra.Command { + return &cobra.Command{ + Use: "version", + Short: "Print the version", + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, _ []string) { fmt.Fprintln(cmd.OutOrStdout(), version) }, + } +} diff --git a/cmd/grus/openapi.go b/cmd/grus/openapi.go index f06e6c1..ecc18a3 100644 --- a/cmd/grus/openapi.go +++ b/cmd/grus/openapi.go @@ -1,17 +1,17 @@ package main import ( - "os" + "io" "github.com/OneLiteFeatherNET/grus/internal/api" ) -// runOpenAPI prints the generated OpenAPI 3.1 document to stdout. -func runOpenAPI() error { +// runOpenAPI prints the generated OpenAPI 3.1 document to w. +func runOpenAPI(w io.Writer) error { doc, err := api.OpenAPI() if err != nil { return err } - _, err = os.Stdout.Write(doc) + _, err = w.Write(doc) return err } diff --git a/go.mod b/go.mod index 9390231..172fc74 100644 --- a/go.mod +++ b/go.mod @@ -6,13 +6,19 @@ require ( github.com/danielgtaylor/huma/v2 v2.41.0 github.com/minio/minio-go/v7 v7.4.1 github.com/pressly/goose/v3 v3.30.1 + github.com/reeflective/console v0.5.0 + github.com/spf13/cobra v1.10.2 + gopkg.in/yaml.v3 v3.0.1 k8s.io/api v0.36.6 k8s.io/apimachinery v0.36.6 k8s.io/client-go v0.36.6 modernc.org/sqlite v1.63.0 + sigs.k8s.io/yaml v1.6.0 ) require ( + github.com/carapace-sh/carapace v1.11.6 // indirect + github.com/carapace-sh/carapace-shlex v1.1.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dustin/go-humanize v1.1.0 // indirect @@ -25,8 +31,10 @@ require ( github.com/google/gnostic-models v0.7.0 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect + github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/klauspost/compress v1.20.4 // indirect github.com/klauspost/cpuid/v2 v2.4.2 // indirect github.com/klauspost/crc32 v1.3.0 // indirect @@ -42,9 +50,12 @@ require ( github.com/ncruces/go-strftime v1.1.0 // indirect github.com/philhofer/fwd v1.2.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/reeflective/readline v1.3.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rivo/uniseg v0.4.7 // indirect github.com/rs/xid v1.6.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect + github.com/spf13/pflag v1.1.0 // indirect github.com/tinylib/msgp v1.6.5 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/zeebo/xxh3 v1.1.0 // indirect @@ -63,7 +74,6 @@ require ( gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/ini.v1 v1.67.3 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/klog/v2 v2.140.0 // indirect k8s.io/kube-openapi v0.0.0-20260317180543-43fb72c5454a // indirect k8s.io/streaming v0.36.6 // indirect @@ -71,8 +81,8 @@ require ( modernc.org/libc v1.80.2 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.12.1 // indirect + mvdan.cc/sh/v3 v3.13.1 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/randfill v1.0.0 // indirect sigs.k8s.io/structured-merge-diff/v6 v6.3.3 // indirect - sigs.k8s.io/yaml v1.6.0 // indirect ) diff --git a/go.sum b/go.sum index e80a33f..f036365 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,15 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= +github.com/carapace-sh/carapace v1.11.6 h1:fUZv+oAMgbiDEpNPNis4n35tzqE3h8yshOohLJ2Mz4Y= +github.com/carapace-sh/carapace v1.11.6/go.mod h1:5MUSHyLN9GGb5/NY/j9VI68/TcZV4ApRCAHGg4WeU0s= +github.com/carapace-sh/carapace-shlex v1.1.1 h1:ccmNeetAYZOk4IcV36youFDsXusT9uCNW2Njkw+QS+Q= +github.com/carapace-sh/carapace-shlex v1.1.1/go.mod h1:lJ4ZsdxytE0wHJ8Ta9S7Qq0XpjgjU0mdfCqiI2FHx7M= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/danielgtaylor/huma/v2 v2.41.0 h1:LqEFny+YOmAsLMxXa5mfT9sHAjhOd65pihHU49NOgYU= github.com/danielgtaylor/huma/v2 v2.41.0/go.mod h1:qScIxkbYjBqNOg21sN4nhT69CC9X8ydMr+/OdJSWqW8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -27,6 +34,8 @@ github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= +github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI= +github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow= github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo= github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= @@ -40,10 +49,16 @@ github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5T github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/hinshun/vt10x v0.0.0-20220301184237-5011da428d02 h1:AgcIVYPa6XJnU3phs104wLj8l5GEththEw6+F79YsIY= +github.com/hinshun/vt10x v0.0.0-20220301184237-5011da428d02/go.mod h1:Q48J4R4DvxnHolD5P8pOtXigYlRuPLGl6moFx3ulM68= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= @@ -89,14 +104,24 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE= github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM= +github.com/reeflective/console v0.5.0 h1:CNNMKxa35nOjQaBp5saQV+tg7l0jmmL3MDAkt5w7b14= +github.com/reeflective/console v0.5.0/go.mod h1:kdGZ6hxATYj2aXIGdAuLhL2ONWpkz1x8QQi2dSZsmB8= +github.com/reeflective/readline v1.3.0 h1:uh9c2SEmyoy7A/auequfXZjvK0NP5HVEAJFcL9Uf7qE= +github.com/reeflective/readline v1.3.0/go.mod h1:bOpqx2/VqGlIoobyWR1Vgt/p5FiMfIHj4OicPuw6RfU= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g= github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag= github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -127,6 +152,7 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= @@ -205,6 +231,8 @@ modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +mvdan.cc/sh/v3 v3.13.1 h1:DP3TfgZhDkT7lerUdnp6PTGKyxxzz6T+cOlY/xEvfWk= +mvdan.cc/sh/v3 v3.13.1/go.mod h1:lXJ8SexMvEVcHCoDvAGLZgFJ9Wsm2sulmoNEXGhYZD0= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= diff --git a/internal/cli/apply.go b/internal/cli/apply.go new file mode 100644 index 0000000..a044688 --- /dev/null +++ b/internal/cli/apply.go @@ -0,0 +1,173 @@ +package cli + +import ( + "bytes" + "errors" + "fmt" + "io" + "os" + "sort" + "strings" + + "github.com/spf13/cobra" + "gopkg.in/yaml.v3" + + "github.com/OneLiteFeatherNET/grus/internal/client" +) + +// apiVersion is the only manifest version the CLI accepts; it matches the CRDs. +const apiVersion = "grus.onelitefeather.net/v1alpha1" + +// manifestKinds maps manifest kinds to API resources. The order is the apply order: what a pool +// refers to comes first. +var manifestKinds = []struct{ kind, resource string }{ + {"Environment", "environments"}, + {"Group", "groups"}, + {"Pool", "pools"}, +} + +type manifest struct { + kind string + resource string + name string + spec map[string]any + source string +} + +// parseManifests decodes every YAML or JSON document of r. A document of kind List expands to its items. +func parseManifests(source string, r io.Reader) ([]manifest, error) { + raw, err := io.ReadAll(r) + if err != nil { + return nil, err + } + dec := yaml.NewDecoder(bytes.NewReader(raw)) + var out []manifest + for n := 1; ; n++ { + var doc map[string]any + if err := dec.Decode(&doc); errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, fmt.Errorf("%s: document %d: %w", source, n, err) + } + if doc == nil { + continue + } + docs := []map[string]any{doc} + if doc["kind"] == "List" { + items, _ := doc["items"].([]any) + docs = docs[:0] + for _, it := range items { + m, ok := it.(map[string]any) + if !ok { + return nil, fmt.Errorf("%s: document %d: list item is not an object", source, n) + } + docs = append(docs, m) + } + } + for _, d := range docs { + m, err := toManifest(d) + if err != nil { + return nil, fmt.Errorf("%s: document %d: %w", source, n, err) + } + m.source = source + out = append(out, m) + } + } + return out, nil +} + +func toManifest(d map[string]any) (manifest, error) { + if v, _ := d["apiVersion"].(string); v != apiVersion { + return manifest{}, fmt.Errorf("apiVersion must be %s", apiVersion) + } + k, _ := d["kind"].(string) + m := manifest{kind: k} + for _, mk := range manifestKinds { + if mk.kind == k { + m.resource = mk.resource + } + } + if m.resource == "" { + return manifest{}, fmt.Errorf("unsupported kind %q, use Environment, Group or Pool", k) + } + meta, _ := d["metadata"].(map[string]any) + m.name, _ = meta["name"].(string) + if m.name == "" { + return manifest{}, errors.New("metadata.name is required") + } + spec, ok := d["spec"].(map[string]any) + if !ok { + return manifest{}, errors.New("spec is required and must be an object") + } + m.spec = spec + return m, nil +} + +func rank(resource string) int { + for i, mk := range manifestKinds { + if mk.resource == resource { + return i + } + } + return len(manifestKinds) +} + +func newApplyCmd(env *Env, o *opts) *cobra.Command { + var files []string + var dryRun bool + cmd := &cobra.Command{ + Use: "apply -f ", + Short: "Create or update Pools, Groups and Environments from YAML or JSON", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if len(files) == 0 { + return errors.New("-f is required") + } + var all []manifest + for _, f := range files { + var r io.Reader + if f == "-" { + r = cmd.InOrStdin() + } else { + fh, err := os.Open(f) + if err != nil { + return err + } + defer fh.Close() + r = fh + } + ms, err := parseManifests(f, r) + if err != nil { + return err + } + all = append(all, ms...) + } + if len(all) == 0 { + return errors.New("no resources found in the given files") + } + sort.SliceStable(all, func(i, j int) bool { return rank(all[i].resource) < rank(all[j].resource) }) + var cl *client.Client + if !dryRun { + var err error + if cl, _, err = o.client(env); err != nil { + return err + } + } + for _, m := range all { + label := strings.ToLower(m.kind) + "/" + m.name + if dryRun { + fmt.Fprintf(cmd.OutOrStdout(), "%s valid (dry run)\n", label) + continue + } + if _, err := cl.Put(cmdContext(cmd), m.resource, m.name, m.spec); err != nil { + return fmt.Errorf("%s (%s): %w", label, m.source, err) + } + fmt.Fprintf(cmd.OutOrStdout(), "%s applied\n", label) + } + return nil + }, + } + cmd.Flags().StringArrayVarP(&files, "filename", "f", nil, "manifest file (YAML or JSON), - for stdin; repeatable") + cmd.Flags().BoolVar(&dryRun, "dry-run", false, "validate the manifests locally without calling the controller") + return cmd +} diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go new file mode 100644 index 0000000..1cbb5c5 --- /dev/null +++ b/internal/cli/cli_test.go @@ -0,0 +1,377 @@ +package cli + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +type fakeClock struct { + mu sync.Mutex + now time.Time +} + +func (c *fakeClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now } +func (c *fakeClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = c.now.Add(d) +} + +// harness runs commands in process against an httptest server with a private config dir. +type harness struct { + t *testing.T + env *Env + vars map[string]string + clock *fakeClock + cfgDir string +} + +func newHarness(t *testing.T, h http.Handler) *harness { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + hn := &harness{t: t, vars: map[string]string{"GRUS_URL": srv.URL, "GRUS_TOKEN": "tok"}, cfgDir: t.TempDir(), + clock: &fakeClock{now: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)}} + hn.env = &Env{ + Getenv: func(k string) string { return hn.vars[k] }, + ConfigDir: func() (string, error) { return hn.cfgDir, nil }, + HTTPClient: srv.Client(), + Clock: hn.clock, + Exit: func(int) {}, + } + return hn +} + +func (h *harness) run(stdin string, args ...string) (string, string, error) { + h.t.Helper() + root := NewRoot(h.env) + var out, errb bytes.Buffer + root.SetOut(&out) + root.SetErr(&errb) + root.SetIn(strings.NewReader(stdin)) + root.SetArgs(args) + err := root.Execute() + return out.String(), errb.String(), err +} + +func (h *harness) ok(stdin string, args ...string) string { + h.t.Helper() + out, _, err := h.run(stdin, args...) + if err != nil { + h.t.Fatalf("grus %s: %v", strings.Join(args, " "), err) + } + return out +} + +const poolsJSON = `[{"name":"lobby","spec":{"role":"game","mode":"static","scaling":{"min":1,"max":4}},"generation":3,"maintenance":false}, +{"name":"proxy","spec":{"role":"proxy","mode":"static","scaling":{"min":2,"max":2}},"generation":1,"maintenance":false}]` + +const instancesJSON = `[{"id":"lobby-abc","pool":"lobby","state":"Ready","players":3,"maxPlayers":20,"host":"k8s","address":"10.0.0.1:25565"}]` + +func apiMux(t *testing.T) *http.ServeMux { + t.Helper() + mux := http.NewServeMux() + mux.HandleFunc("GET /v1/pools", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, poolsJSON) }) + mux.HandleFunc("GET /v1/instances", func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("pool") == "none" { + io.WriteString(w, `[]`) + return + } + io.WriteString(w, instancesJSON) + }) + mux.HandleFunc("GET /v1/templates", func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `{"paper":{"stable":"sha256:0123456789abcdef0123"}}`) + }) + return mux +} + +func TestGetPoolsTable(t *testing.T) { + h := newHarness(t, apiMux(t)) + out := h.ok("", "get", "pools") + for _, want := range []string{"NAME", "lobby", "proxy", "GENERATION"} { + if !strings.Contains(out, want) { + t.Errorf("table lacks %q:\n%s", want, out) + } + } +} + +func TestGetPoolsJSONIsAnArray(t *testing.T) { + h := newHarness(t, apiMux(t)) + var got []map[string]any + if err := json.Unmarshal([]byte(h.ok("", "get", "pools", "-o", "json")), &got); err != nil || len(got) != 2 { + t.Fatalf("json output: %v (%d items)", err, len(got)) + } +} + +func TestGetPoolsYAML(t *testing.T) { + h := newHarness(t, apiMux(t)) + if out := h.ok("", "get", "pools", "-o", "yaml"); !strings.Contains(out, " name: lobby") { + t.Errorf("yaml output:\n%s", out) + } +} + +func TestGetInstancesPassesFilters(t *testing.T) { + var q string + mux := apiMux(t) + mux.HandleFunc("GET /v1/instances/{id}", func(w http.ResponseWriter, r *http.Request) {}) + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q = r.URL.RawQuery + mux.ServeHTTP(w, r) + })) + out := h.ok("", "get", "instances", "--pool", "lobby", "--state", "Ready") + if !strings.Contains(q, "pool=lobby") || !strings.Contains(q, "state=Ready") { + t.Errorf("query = %q", q) + } + if !strings.Contains(out, "3/20") { + t.Errorf("players column missing:\n%s", out) + } +} + +func TestGetTemplatesShortensDigests(t *testing.T) { + h := newHarness(t, apiMux(t)) + out := h.ok("", "get", "templates") + if !strings.Contains(out, "stable=sha256:0123456789ab") || strings.Contains(out, "cdef0123") { + t.Errorf("templates:\n%s", out) + } +} + +func TestGetUnknownResourceListsChoices(t *testing.T) { + h := newHarness(t, apiMux(t)) + _, _, err := h.run("", "get", "widgets") + if err == nil || !strings.Contains(err.Error(), "pools, instances") { + t.Errorf("err = %v", err) + } +} + +func TestGetGroupsOnOldControllerSaysNotSupported(t *testing.T) { + h := newHarness(t, apiMux(t)) + _, _, err := h.run("", "get", "groups") + if err == nil || !strings.Contains(err.Error(), "not supported by this controller") { + t.Errorf("err = %v", err) + } +} + +func TestGetHostsOnNewerController(t *testing.T) { + mux := apiMux(t) + mux.HandleFunc("GET /v1/hosts", func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `[{"name":"mc01","version":"2.0.0","capacity":{"memoryMiB":16384},"addresses":["10.1.1.1"]}]`) + }) + h := newHarness(t, mux) + out := h.ok("", "get", "hosts") + if !strings.Contains(out, "mc01") || !strings.Contains(out, "16384") { + t.Errorf("hosts:\n%s", out) + } +} + +func TestDescribePoolShowsSpecAndInstances(t *testing.T) { + mux := apiMux(t) + mux.HandleFunc("GET /v1/pools/lobby", func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `{"name":"lobby","spec":{"role":"game"},"generation":3}`) + }) + h := newHarness(t, mux) + out := h.ok("", "describe", "pool", "lobby") + if !strings.Contains(out, "role: game") || !strings.Contains(out, "lobby-abc") { + t.Errorf("describe:\n%s", out) + } +} + +func TestApplyOrdersKindsAndPutsSpec(t *testing.T) { + var mu sync.Mutex + var calls []string + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + calls = append(calls, r.Method+" "+r.URL.Path+" "+string(b)) + mu.Unlock() + io.WriteString(w, `{}`) + })) + manifest := `apiVersion: grus.onelitefeather.net/v1alpha1 +kind: Pool +metadata: + name: lobby +spec: + role: game + scaling: {min: 1, max: 2} +--- +apiVersion: grus.onelitefeather.net/v1alpha1 +kind: Environment +metadata: + name: paper +spec: + kind: jvm +` + out := h.ok(manifest, "apply", "-f", "-") + if len(calls) != 2 || !strings.HasPrefix(calls[0], "PUT /v1/environments/paper ") || !strings.HasPrefix(calls[1], "PUT /v1/pools/lobby ") { + t.Fatalf("calls = %q", calls) + } + if !strings.Contains(calls[1], `"scaling":{"max":2,"min":1}`) { + t.Errorf("pool body = %s", calls[1]) + } + if !strings.Contains(out, "environment/paper applied") || !strings.Contains(out, "pool/lobby applied") { + t.Errorf("out = %q", out) + } +} + +func TestApplyAcceptsJSONFile(t *testing.T) { + var path string + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path = r.URL.Path; io.WriteString(w, `{}`) })) + f := filepath.Join(t.TempDir(), "g.json") + if err := os.WriteFile(f, []byte(`{"apiVersion":"grus.onelitefeather.net/v1alpha1","kind":"Group","metadata":{"name":"g"},"spec":{"templates":[]}}`), 0o600); err != nil { + t.Fatal(err) + } + h.ok("", "apply", "-f", f) + if path != "/v1/groups/g" { + t.Errorf("path = %q", path) + } +} + +func TestApplyRejectsBadManifests(t *testing.T) { + h := newHarness(t, http.NotFoundHandler()) + cases := map[string]string{ + "wrong apiVersion": "apiVersion: v1\nkind: Pool\nmetadata: {name: a}\nspec: {}\n", + "unknown kind": "apiVersion: grus.onelitefeather.net/v1alpha1\nkind: Server\nmetadata: {name: a}\nspec: {}\n", + "no name": "apiVersion: grus.onelitefeather.net/v1alpha1\nkind: Pool\nmetadata: {}\nspec: {}\n", + "no spec": "apiVersion: grus.onelitefeather.net/v1alpha1\nkind: Pool\nmetadata: {name: a}\n", + } + for name, doc := range cases { + if _, _, err := h.run(doc, "apply", "-f", "-"); err == nil { + t.Errorf("%s: want an error", name) + } + } +} + +func TestApplyDryRunDoesNotCallController(t *testing.T) { + called := false + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true })) + out := h.ok("apiVersion: grus.onelitefeather.net/v1alpha1\nkind: Pool\nmetadata: {name: a}\nspec: {role: game}\n", + "apply", "-f", "-", "--dry-run") + if called || !strings.Contains(out, "valid (dry run)") { + t.Errorf("called=%v out=%q", called, out) + } +} + +func TestScaleChangesOnlyMinAndKeepsTheRestOfTheSpec(t *testing.T) { + var put string + mux := http.NewServeMux() + mux.HandleFunc("GET /v1/pools/lobby", func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `{"name":"lobby","spec":{"role":"game","scaling":{"min":1,"max":4}}}`) + }) + mux.HandleFunc("PUT /v1/pools/lobby", func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + put = string(b) + io.WriteString(w, `{}`) + }) + h := newHarness(t, mux) + out := h.ok("", "scale", "lobby", "--min", "3") + if put != `{"role":"game","scaling":{"max":4,"min":3}}` { + t.Errorf("put body = %s", put) + } + if !strings.Contains(out, "min=3 max=4") { + t.Errorf("out = %q", out) + } + if _, _, err := h.run("", "scale", "lobby"); err == nil { + t.Error("scale without flags must fail") + } +} + +func TestStopSendsDrain(t *testing.T) { + var body string + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + body = string(b) + io.WriteString(w, `{"state":"Draining"}`) + })) + out := h.ok("", "stop", "lobby-abc", "--drain") + if !strings.Contains(body, `"drain":true`) || !strings.Contains(out, "Draining") { + t.Errorf("body=%s out=%q", body, out) + } + if _, _, err := h.run("", "stop", "x", "--drain", "--force"); err == nil { + t.Error("drain and force together must fail") + } +} + +func TestExecJoinsTheConsoleLine(t *testing.T) { + var body string + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + body = string(b) + w.WriteHeader(http.StatusNoContent) + })) + h.ok("", "exec", "lobby-abc", "--", "say", "hello", "world") + if body != `{"line":"say hello world"}` { + t.Errorf("body = %s", body) + } +} + +func TestLogsTailAndFollow(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /v1/instances/i/logs", func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "tail="+r.URL.Query().Get("tail")+"\n") + }) + mux.HandleFunc("GET /v1/instances/i/logs/stream", func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "data: one\n\ndata: two\n\n") + }) + h := newHarness(t, mux) + if out := h.ok("", "logs", "i", "--tail", "7"); out != "tail=7\n" { + t.Errorf("tail out = %q", out) + } + if out := h.ok("", "logs", "i", "-f"); out != "one\ntwo\n" { + t.Errorf("follow out = %q", out) + } +} + +func TestEventsFilterByType(t *testing.T) { + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "id: 1\nevent: pool.updated\ndata: {\"a\":1}\n\nid: 2\nevent: instance.state\ndata: {\"b\":2}\n\n") + })) + out := h.ok("", "events", "--type", "instance.") + if strings.Contains(out, "pool.updated") || !strings.Contains(out, "instance.state") { + t.Errorf("out = %q", out) + } + out = h.ok("", "events", "-o", "json") + if lines := strings.Split(strings.TrimSpace(out), "\n"); len(lines) != 2 || !strings.Contains(lines[0], `"type":"pool.updated"`) { + t.Errorf("json lines = %q", lines) + } +} + +func TestNetwork(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /v1/network", func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `{"players":42,"maxPlayers":500,"proxies":2}`) + }) + h := newHarness(t, mux) + if out := h.ok("", "network"); !strings.Contains(out, "42") || !strings.Contains(out, "PROXIES") { + t.Errorf("out = %q", out) + } + old := newHarness(t, http.NotFoundHandler()) + if _, _, err := old.run("", "network"); err == nil || !strings.Contains(err.Error(), "not supported by this controller") { + t.Errorf("err = %v", err) + } +} + +func TestInvalidOutputFormatIsRejected(t *testing.T) { + h := newHarness(t, apiMux(t)) + if _, _, err := h.run("", "get", "pools", "-o", "xml"); err == nil { + t.Error("want an error for -o xml") + } +} + +func TestAPIErrorIsReportedWithStatus(t *testing.T) { + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + io.WriteString(w, `{"title":"Unauthorized"}`) + })) + _, _, err := h.run("", "get", "pools") + if err == nil || !strings.Contains(err.Error(), "401") { + t.Errorf("err = %v", err) + } +} diff --git a/internal/cli/complete.go b/internal/cli/complete.go new file mode 100644 index 0000000..bb3000e --- /dev/null +++ b/internal/cli/complete.go @@ -0,0 +1,148 @@ +package cli + +import ( + "sort" + "strings" + "sync" + "time" + + "github.com/spf13/cobra" + + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +// nameCache keeps completion candidates for a short time so tab presses do not hit the API every time. +// The clock is injected; entries older than ttl are refetched. +type nameCache struct { + clock model.Clock + ttl time.Duration + + mu sync.Mutex + entries map[string]cacheEntry +} + +type cacheEntry struct { + at time.Time + names []string +} + +func newNameCache(clock model.Clock, ttl time.Duration) *nameCache { + return &nameCache{clock: clock, ttl: ttl, entries: map[string]cacheEntry{}} +} + +// get returns the cached names for key or loads them. +func (c *nameCache) get(key string, load func() ([]string, error)) ([]string, error) { + c.mu.Lock() + defer c.mu.Unlock() + now := c.clock.Now() + if e, ok := c.entries[key]; ok && now.Sub(e.at) < c.ttl { + return e.names, nil + } + names, err := load() + if err != nil { + return nil, err + } + c.entries[key] = cacheEntry{at: now, names: names} + return names, nil +} + +type completeFunc = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) + +// resourceNames returns the names of a resource through the cache. The key includes the controller URL. +func resourceNames(cmd *cobra.Command, env *Env, o *opts, resource string) ([]string, error) { + c, conn, err := o.client(env) + if err != nil { + return nil, err + } + return env.cache.get(conn.URL+"|"+resource, func() ([]string, error) { + k, err := lookupKind(resource) + if err != nil { + return nil, err + } + items, err := fetchAll(cmd, c, k, nil) + if err != nil { + return nil, err + } + key := "name" + if resource == "instances" { + key = "id" + } + names := make([]string, 0, len(items)) + for _, it := range items { + if n, _ := it[key].(string); n != "" { + names = append(names, n) + } + } + sort.Strings(names) + return names, nil + }) +} + +func filterPrefix(names []string, prefix string) []string { + var out []string + for _, n := range names { + if strings.HasPrefix(n, prefix) { + out = append(out, n) + } + } + return out +} + +// completeResource completes the names of one resource. +func completeResource(env *Env, o *opts, resource string) completeFunc { + return func(cmd *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) { + names, err := resourceNames(cmd, env, o, resource) + if err != nil { + // Completion must never print errors into the user's line; no candidates is the honest answer. + return nil, cobra.ShellCompDirectiveNoFileComp + } + return filterPrefix(names, toComplete), cobra.ShellCompDirectiveNoFileComp + } +} + +// completeFirstArg applies f for the first positional argument only. +func completeFirstArg(f completeFunc) completeFunc { + return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if len(args) > 0 { + return nil, cobra.ShellCompDirectiveNoFileComp + } + return f(cmd, args, toComplete) + } +} + +// completeKindAndName completes the resource kind first, then the names of that kind. +func completeKindAndName(env *Env, o *opts) completeFunc { + return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + switch len(args) { + case 0: + return filterPrefix(kindNames(), toComplete), cobra.ShellCompDirectiveNoFileComp + case 1: + k, err := lookupKind(args[0]) + if err != nil { + return nil, cobra.ShellCompDirectiveNoFileComp + } + return completeResource(env, o, k.name)(cmd, args, toComplete) + } + return nil, cobra.ShellCompDirectiveNoFileComp + } +} + +func fixed(values ...string) completeFunc { + return func(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return filterPrefix(values, toComplete), cobra.ShellCompDirectiveNoFileComp + } +} + +func completeContexts(env *Env) completeFunc { + return func(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) { + cfg, err := env.loadConfig() + if err != nil { + return nil, cobra.ShellCompDirectiveNoFileComp + } + var names []string + for _, c := range cfg.Contexts { + names = append(names, c.Name) + } + return filterPrefix(names, toComplete), cobra.ShellCompDirectiveNoFileComp + } +} diff --git a/internal/cli/complete_test.go b/internal/cli/complete_test.go new file mode 100644 index 0000000..dd415b2 --- /dev/null +++ b/internal/cli/complete_test.go @@ -0,0 +1,115 @@ +package cli + +import ( + "io" + "net/http" + "strings" + "sync/atomic" + "testing" + "time" +) + +// completionHarness counts the list calls the API receives. +func completionHarness(t *testing.T) (*harness, *atomic.Int32) { + t.Helper() + var calls atomic.Int32 + mux := apiMux(t) + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/pools" { + calls.Add(1) + } + mux.ServeHTTP(w, r) + })) + return h, &calls +} + +func complete(h *harness, args ...string) []string { + h.t.Helper() + out := h.ok("", append([]string{"__complete"}, args...)...) + var got []string + for _, l := range strings.Split(strings.TrimSpace(out), "\n") { + if l != "" && !strings.HasPrefix(l, ":") { + got = append(got, l) + } + } + return got +} + +func TestCompleteKindsThenPoolNames(t *testing.T) { + h, _ := completionHarness(t) + if got := complete(h, "get", "po"); strings.Join(got, ",") != "pools" { + t.Errorf("kinds = %v", got) + } + if got := complete(h, "get", "pools", "l"); strings.Join(got, ",") != "lobby" { + t.Errorf("pool names = %v", got) + } + if got := complete(h, "describe", "pool", ""); strings.Join(got, ",") != "lobby,proxy" { + t.Errorf("describe names = %v", got) + } +} + +func TestCompleteInstancesForLogsStopExec(t *testing.T) { + h, _ := completionHarness(t) + for _, c := range []string{"logs", "stop", "exec"} { + if got := complete(h, c, ""); strings.Join(got, ",") != "lobby-abc" { + t.Errorf("%s: %v", c, got) + } + } + if got := complete(h, "logs", "lobby-abc", ""); len(got) != 0 { + t.Errorf("second argument must not complete, got %v", got) + } +} + +func TestCompletePoolFlagAndScale(t *testing.T) { + h, _ := completionHarness(t) + if got := complete(h, "get", "instances", "--pool", "p"); strings.Join(got, ",") != "proxy" { + t.Errorf("--pool = %v", got) + } + if got := complete(h, "scale", ""); strings.Join(got, ",") != "lobby,proxy" { + t.Errorf("scale = %v", got) + } +} + +func TestCompletionCacheExpiresWithTheInjectedClock(t *testing.T) { + h, calls := completionHarness(t) + complete(h, "scale", "") + complete(h, "scale", "l") + if calls.Load() != 1 { + t.Fatalf("API calls within the TTL = %d, want 1", calls.Load()) + } + h.clock.advance(completionTTL + time.Second) + complete(h, "scale", "") + if calls.Load() != 2 { + t.Errorf("API calls after the TTL = %d, want 2", calls.Load()) + } +} + +func TestCompletionFailureYieldsNoCandidates(t *testing.T) { + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + io.WriteString(w, `{}`) + })) + if got := complete(h, "scale", ""); len(got) != 0 { + t.Errorf("got %v", got) + } +} + +func TestCompleteOutputFormatsAndContexts(t *testing.T) { + h, _ := completionHarness(t) + h.ok("", "login", "--url", "http://x", "--name", "prod") + if got := complete(h, "get", "pools", "-o", ""); strings.Join(got, ",") != "table,json,yaml" { + t.Errorf("formats = %v", got) + } + if got := complete(h, "get", "pools", "--context", "p"); strings.Join(got, ",") != "prod" { + t.Errorf("contexts = %v", got) + } +} + +func TestShellCompletionScriptsExist(t *testing.T) { + h, _ := completionHarness(t) + for _, sh := range []string{"bash", "zsh", "fish", "powershell"} { + if out := h.ok("", "completion", sh); out == "" { + t.Errorf("completion %s printed nothing", sh) + } + } +} diff --git a/internal/cli/config.go b/internal/cli/config.go new file mode 100644 index 0000000..d140d1c --- /dev/null +++ b/internal/cli/config.go @@ -0,0 +1,262 @@ +package cli + +import ( + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/spf13/cobra" + "gopkg.in/yaml.v3" +) + +const ( + configDirName = "grus" + configFileName = "config.yaml" +) + +// fileContext is one named controller connection in the config file. It stores the path of a token +// file, never the token itself. +type fileContext struct { + Name string `yaml:"name"` + URL string `yaml:"url"` + TokenFile string `yaml:"token-file,omitempty"` +} + +// fileConfig is the content of ~/.config/grus/config.yaml. +type fileConfig struct { + Current string `yaml:"current-context,omitempty"` + Contexts []fileContext `yaml:"contexts,omitempty"` +} + +func (c *fileConfig) find(name string) *fileContext { + for i := range c.Contexts { + if c.Contexts[i].Name == name { + return &c.Contexts[i] + } + } + return nil +} + +func (c *fileConfig) set(ctx fileContext) { + if existing := c.find(ctx.Name); existing != nil { + *existing = ctx + return + } + c.Contexts = append(c.Contexts, ctx) +} + +func (e *Env) configDir() (string, error) { + base, err := e.ConfigDir() + if err != nil { + return "", fmt.Errorf("find the user config directory: %w", err) + } + return filepath.Join(base, configDirName), nil +} + +// loadConfig reads the config file; a missing file is an empty config. +func (e *Env) loadConfig() (fileConfig, error) { + dir, err := e.configDir() + if err != nil { + return fileConfig{}, nil //nolint:nilerr // no config dir means no saved contexts; flags and env still work + } + raw, err := os.ReadFile(filepath.Join(dir, configFileName)) + if errors.Is(err, fs.ErrNotExist) { + return fileConfig{}, nil + } + if err != nil { + return fileConfig{}, err + } + var cfg fileConfig + if err := yaml.Unmarshal(raw, &cfg); err != nil { + return fileConfig{}, fmt.Errorf("parse %s: %w", filepath.Join(dir, configFileName), err) + } + return cfg, nil +} + +func (e *Env) saveConfig(cfg fileConfig) error { + dir, err := e.configDir() + if err != nil { + return err + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + raw, err := yaml.Marshal(cfg) + if err != nil { + return err + } + return os.WriteFile(filepath.Join(dir, configFileName), raw, 0o600) +} + +// connection is the resolved way to reach a controller. +type connection struct { + Context string + URL string + Token string +} + +// resolve combines flags, environment and the config file. Precedence for the URL: --url, GRUS_URL, context. +// Token: GRUS_TOKEN, --token-file, token file of the context. +func (e *Env) resolve(o *opts) (connection, error) { + cfg, err := e.loadConfig() + if err != nil { + return connection{}, err + } + name := o.context + if name == "" { + name = cfg.Current + } + var entry fileContext + if name != "" { + found := cfg.find(name) + if found == nil { + return connection{}, fmt.Errorf("unknown context %q, see grus config list", name) + } + entry = *found + } + conn := connection{Context: name, URL: firstNonEmpty(o.url, e.Getenv("GRUS_URL"), entry.URL)} + if conn.URL == "" { + return connection{}, errors.New("no controller URL: run grus login --url , pass --url or set GRUS_URL") + } + conn.Token = strings.TrimSpace(e.Getenv("GRUS_TOKEN")) + if conn.Token == "" { + if file := firstNonEmpty(o.tokenFile, entry.TokenFile); file != "" { + raw, err := os.ReadFile(file) + if err != nil { + return connection{}, fmt.Errorf("read token file: %w", err) + } + conn.Token = strings.TrimSpace(string(raw)) + } + } + return conn, nil +} + +func firstNonEmpty(vals ...string) string { + for _, v := range vals { + if v != "" { + return v + } + } + return "" +} + +func newLoginCmd(env *Env) *cobra.Command { + var name, url, tokenFile string + var tokenStdin bool + cmd := &cobra.Command{ + Use: "login --url [--name ] [--token-file | --token-stdin]", + Short: "Save a controller connection as a context and make it current", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if url == "" { + return errors.New("--url is required") + } + if tokenFile != "" && tokenStdin { + return errors.New("use either --token-file or --token-stdin") + } + dir, err := env.configDir() + if err != nil { + return err + } + if tokenStdin { + raw, err := io.ReadAll(cmd.InOrStdin()) + if err != nil { + return err + } + token := strings.TrimSpace(string(raw)) + if token == "" { + return errors.New("no token on stdin") + } + tokenFile = filepath.Join(dir, "tokens", name) + if err := os.MkdirAll(filepath.Dir(tokenFile), 0o700); err != nil { + return err + } + if err := os.WriteFile(tokenFile, []byte(token+"\n"), 0o600); err != nil { + return err + } + } else if tokenFile != "" { + if tokenFile, err = filepath.Abs(tokenFile); err != nil { + return err + } + } + cfg, err := env.loadConfig() + if err != nil { + return err + } + cfg.set(fileContext{Name: name, URL: strings.TrimRight(url, "/"), TokenFile: tokenFile}) + cfg.Current = name + if err := env.saveConfig(cfg); err != nil { + return err + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "context %q saved and selected\n", name) + return err + }, + } + cmd.Flags().StringVar(&name, "name", "default", "context name") + cmd.Flags().StringVar(&url, "url", "", "controller base URL") + cmd.Flags().StringVar(&tokenFile, "token-file", "", "file holding the API token") + cmd.Flags().BoolVar(&tokenStdin, "token-stdin", false, "read the token from stdin and store it in a private file") + return cmd +} + +func newConfigCmd(env *Env) *cobra.Command { + cmd := &cobra.Command{Use: "config", Short: "Manage saved contexts"} + cmd.AddCommand(&cobra.Command{ + Use: "list", Short: "List the saved contexts", Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + cfg, err := env.loadConfig() + if err != nil { + return err + } + items := make([]map[string]any, 0, len(cfg.Contexts)) + for _, c := range cfg.Contexts { + current := "" + if c.Name == cfg.Current { + current = "*" + } + items = append(items, map[string]any{"name": c.Name, "url": c.URL, "tokenFile": c.TokenFile, "current": current}) + } + return printList(cmd, outputFormat(cmd), items, []column{ + {"CURRENT", field("current")}, {"NAME", field("name")}, {"URL", field("url")}, {"TOKEN-FILE", field("tokenFile")}, + }) + }, + }) + cmd.AddCommand(&cobra.Command{ + Use: "current", Short: "Print the current context name", Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + cfg, err := env.loadConfig() + if err != nil { + return err + } + if cfg.Current == "" { + return errors.New("no current context, run grus login") + } + _, err = fmt.Fprintln(cmd.OutOrStdout(), cfg.Current) + return err + }, + }) + cmd.AddCommand(&cobra.Command{ + Use: "use ", Short: "Select the current context", Args: cobra.ExactArgs(1), + ValidArgsFunction: completeContexts(env), + RunE: func(cmd *cobra.Command, args []string) error { + cfg, err := env.loadConfig() + if err != nil { + return err + } + if cfg.find(args[0]) == nil { + return fmt.Errorf("unknown context %q", args[0]) + } + cfg.Current = args[0] + if err := env.saveConfig(cfg); err != nil { + return err + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "current context is %q\n", args[0]) + return err + }, + }) + return cmd +} diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go new file mode 100644 index 0000000..4022808 --- /dev/null +++ b/internal/cli/config_test.go @@ -0,0 +1,112 @@ +package cli + +import ( + "net/http" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestLoginStoresTokenInPrivateFileAndNeverPrintsIt(t *testing.T) { + h := newHarness(t, http.NotFoundHandler()) + out := h.ok("super-secret-token\n", "login", "--url", "https://grus.example/", "--name", "prod", "--token-stdin") + if strings.Contains(out, "super-secret-token") { + t.Fatalf("login printed the token: %q", out) + } + tokenFile := filepath.Join(h.cfgDir, "grus", "tokens", "prod") + info, err := os.Stat(tokenFile) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Errorf("token file mode = %v, want 0600", info.Mode().Perm()) + } + cfg, err := os.ReadFile(filepath.Join(h.cfgDir, "grus", "config.yaml")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(cfg), "super-secret-token") || !strings.Contains(string(cfg), "url: https://grus.example") { + t.Errorf("config:\n%s", cfg) + } +} + +func TestContextSuppliesURLAndTokenFile(t *testing.T) { + var gotAuth string + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + _, _ = w.Write([]byte(`[]`)) + })) + url := h.vars["GRUS_URL"] + delete(h.vars, "GRUS_URL") + delete(h.vars, "GRUS_TOKEN") + h.ok("filetoken\n", "login", "--url", url, "--token-stdin") + h.ok("", "get", "pools") + if gotAuth != "Bearer filetoken" { + t.Errorf("Authorization = %q", gotAuth) + } +} + +func TestEnvTokenBeatsTokenFile(t *testing.T) { + var gotAuth string + h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + _, _ = w.Write([]byte(`[]`)) + })) + h.ok("filetoken", "login", "--url", h.vars["GRUS_URL"], "--token-stdin") + h.vars["GRUS_TOKEN"] = "envtoken" + h.ok("", "get", "pools") + if gotAuth != "Bearer envtoken" { + t.Errorf("Authorization = %q", gotAuth) + } +} + +func TestNoURLGivesActionableError(t *testing.T) { + h := newHarness(t, http.NotFoundHandler()) + delete(h.vars, "GRUS_URL") + _, _, err := h.run("", "get", "pools") + if err == nil || !strings.Contains(err.Error(), "grus login") { + t.Errorf("err = %v", err) + } +} + +func TestConfigUseSwitchesAndRejectsUnknown(t *testing.T) { + h := newHarness(t, http.NotFoundHandler()) + h.ok("", "login", "--url", "http://a", "--name", "a") + h.ok("", "login", "--url", "http://b", "--name", "b") + if got := strings.TrimSpace(h.ok("", "config", "current")); got != "b" { + t.Errorf("current = %q", got) + } + h.ok("", "config", "use", "a") + if got := strings.TrimSpace(h.ok("", "config", "current")); got != "a" { + t.Errorf("current = %q", got) + } + if _, _, err := h.run("", "config", "use", "zzz"); err == nil { + t.Error("unknown context must fail") + } + if out := h.ok("", "config", "list"); !strings.Contains(out, "http://b") { + t.Errorf("list:\n%s", out) + } +} + +func TestPromptShowsContextName(t *testing.T) { + if got := promptFor(connection{Context: "prod"}); got != "grus(prod)> " { + t.Errorf("prompt = %q", got) + } + if got := promptFor(connection{}); got != "grus(-)> " { + t.Errorf("prompt without context = %q", got) + } +} + +func TestShellTreeHasExitButNoNestedShell(t *testing.T) { + env := &Env{Exit: func(int) {}} + env.ensure() + root := newRoot(env, opts{output: formatTable}, true) + names := map[string]bool{} + for _, c := range root.Commands() { + names[c.Name()] = true + } + if !names["exit"] || names["shell"] || !names["get"] { + t.Errorf("commands = %v", names) + } +} diff --git a/internal/cli/env.go b/internal/cli/env.go new file mode 100644 index 0000000..9ef9be2 --- /dev/null +++ b/internal/cli/env.go @@ -0,0 +1,51 @@ +// Package cli implements the client side of the grus command: resource commands, contexts and the REPL. +package cli + +import ( + "net/http" + "os" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +// completionTTL is how long completion candidates are reused before the API is asked again. +const completionTTL = 5 * time.Second + +// Env carries everything the commands take from the outside world, so tests can replace it. +type Env struct { + // Getenv reads environment variables; defaults to os.Getenv. + Getenv func(string) string + // ConfigDir returns the user config directory; defaults to os.UserConfigDir. + ConfigDir func() (string, error) + // HTTPClient is used for every API call; defaults to a client without a global timeout. + HTTPClient *http.Client + // Clock drives the completion cache; defaults to the system clock. + Clock model.Clock + // Exit ends the process (the shell's exit command); defaults to os.Exit. + Exit func(int) + + cache *nameCache +} + +// ensure fills the defaults. It is idempotent. +func (e *Env) ensure() { + if e.Getenv == nil { + e.Getenv = os.Getenv + } + if e.ConfigDir == nil { + e.ConfigDir = os.UserConfigDir + } + if e.HTTPClient == nil { + e.HTTPClient = &http.Client{} + } + if e.Clock == nil { + e.Clock = model.SystemClock{} + } + if e.Exit == nil { + e.Exit = os.Exit + } + if e.cache == nil { + e.cache = newNameCache(e.Clock, completionTTL) + } +} diff --git a/internal/cli/get.go b/internal/cli/get.go new file mode 100644 index 0000000..a93341c --- /dev/null +++ b/internal/cli/get.go @@ -0,0 +1,220 @@ +package cli + +import ( + "errors" + "fmt" + "net/url" + "sort" + "strings" + + "github.com/spf13/cobra" + + "github.com/OneLiteFeatherNET/grus/internal/client" +) + +// kind describes one resource type of the API as the CLI shows it. +type kind struct { + name string // plural, also the API path segment + aliases []string + cols []column + newNames bool // false for resources every controller serves +} + +var kinds = []kind{ + {name: "pools", aliases: []string{"pool", "po"}, cols: []column{ + {"NAME", field("name")}, {"ROLE", field("spec", "role")}, {"MODE", field("spec", "mode")}, + {"MIN", field("spec", "scaling", "min")}, {"MAX", field("spec", "scaling", "max")}, + {"GENERATION", field("generation")}, {"MAINTENANCE", field("maintenance")}, + }}, + {name: "instances", aliases: []string{"instance", "inst", "i"}, cols: []column{ + {"ID", field("id")}, {"POOL", field("pool")}, {"STATE", field("state")}, + {"PLAYERS", func(o object) string { return field("players")(o) + "/" + field("maxPlayers")(o) }}, + {"HOST", field("host")}, {"ADDRESS", field("address")}, + }}, + {name: "templates", aliases: []string{"template", "tpl"}, cols: []column{ + {"NAME", field("name")}, {"TAGS", templateTags}, + }}, + {name: "groups", aliases: []string{"group", "grp"}, newNames: true, cols: []column{ + {"NAME", field("name")}, {"TEMPLATES", field("spec", "templates")}, {"LABELS", field("spec", "labels")}, + }}, + {name: "environments", aliases: []string{"environment", "env"}, newNames: true, cols: []column{ + {"NAME", field("name")}, {"KIND", field("spec", "kind")}, {"IMAGE", field("spec", "image")}, + {"PORT", field("spec", "port")}, {"READINESS", field("spec", "readiness")}, + }}, + {name: "hosts", aliases: []string{"host"}, newNames: true, cols: []column{ + {"NAME", field("name")}, {"VERSION", field("version")}, {"MEMORY-MIB", field("capacity", "memoryMiB")}, + {"ADDRESSES", field("addresses")}, {"LAST-SEEN", field("lastSeen")}, + }}, +} + +func kindNames() []string { + out := make([]string, len(kinds)) + for i, k := range kinds { + out[i] = k.name + } + return out +} + +func lookupKind(name string) (kind, error) { + n := strings.ToLower(name) + for _, k := range kinds { + if k.name == n { + return k, nil + } + for _, a := range k.aliases { + if a == n { + return k, nil + } + } + } + return kind{}, fmt.Errorf("unknown resource %q, use one of: %s", name, strings.Join(kindNames(), ", ")) +} + +func templateTags(o object) string { + tags, _ := o["tags"].(map[string]any) + keys := make([]string, 0, len(tags)) + for k := range tags { + keys = append(keys, k) + } + sort.Strings(keys) + parts := make([]string, 0, len(keys)) + for _, k := range keys { + d, _ := tags[k].(string) + if len(d) > len("sha256:")+12 { + d = d[:len("sha256:")+12] + } + parts = append(parts, k+"="+d) + } + return strings.Join(parts, " ") +} + +// fetchAll lists a resource. Templates come as a map from the API and are turned into objects. +func fetchAll(cmd *cobra.Command, c *client.Client, k kind, q url.Values) ([]object, error) { + if k.name != "templates" { + return c.List(cmdContext(cmd), k.name, q) + } + all, err := c.Templates(cmdContext(cmd)) + if err != nil { + return nil, err + } + names := make([]string, 0, len(all)) + for n := range all { + names = append(names, n) + } + sort.Strings(names) + out := make([]object, 0, len(names)) + for _, n := range names { + tags := make(map[string]any, len(all[n])) + for t, d := range all[n] { + tags[t] = d + } + out = append(out, object{"name": n, "tags": tags}) + } + return out, nil +} + +func fetchOne(cmd *cobra.Command, c *client.Client, k kind, name string) (object, error) { + if k.name == "templates" { + all, err := fetchAll(cmd, c, k, nil) + if err != nil { + return nil, err + } + for _, o := range all { + if o["name"] == name { + return o, nil + } + } + return nil, fmt.Errorf("template %q not found", name) + } + return c.Get(cmdContext(cmd), k.name, name) +} + +func newGetCmd(env *Env, o *opts) *cobra.Command { + var pool, state, role string + cmd := &cobra.Command{ + Use: "get [name]", + Short: "List resources or show one", + Args: cobra.RangeArgs(1, 2), + RunE: func(cmd *cobra.Command, args []string) error { + k, err := lookupKind(args[0]) + if err != nil { + return err + } + c, _, err := o.client(env) + if err != nil { + return err + } + if len(args) == 2 { + obj, err := fetchOne(cmd, c, k, args[1]) + if err != nil { + return err + } + if o.output == formatTable { + return printList(cmd, o.output, []object{obj}, k.cols) + } + return printObject(cmd, o.output, obj) + } + q := url.Values{} + if k.name == "instances" { + for key, v := range map[string]string{"pool": pool, "state": state, "role": role} { + if v != "" { + q.Set(key, v) + } + } + } else if pool != "" || state != "" || role != "" { + return errors.New("--pool, --state and --role only apply to instances") + } + items, err := fetchAll(cmd, c, k, q) + if err != nil { + return err + } + return printList(cmd, o.output, items, k.cols) + }, + ValidArgsFunction: completeKindAndName(env, o), + } + cmd.Flags().StringVar(&pool, "pool", "", "only instances of this pool") + cmd.Flags().StringVar(&state, "state", "", "only instances in this state") + cmd.Flags().StringVar(&role, "role", "", "only instances with this role (proxy, game, other)") + _ = cmd.RegisterFlagCompletionFunc("pool", completeResource(env, o, "pools")) + _ = cmd.RegisterFlagCompletionFunc("role", fixed("proxy", "game", "other")) + return cmd +} + +func newDescribeCmd(env *Env, o *opts) *cobra.Command { + return &cobra.Command{ + Use: "describe ", + Short: "Show one resource in detail; a pool also lists its instances", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + k, err := lookupKind(args[0]) + if err != nil { + return err + } + c, _, err := o.client(env) + if err != nil { + return err + } + obj, err := fetchOne(cmd, c, k, args[1]) + if err != nil { + return err + } + if err := printObject(cmd, o.output, obj); err != nil { + return err + } + if k.name != "pools" || o.output != formatTable { + return nil + } + insts, err := c.List(cmdContext(cmd), "instances", url.Values{"pool": {args[1]}}) + if err != nil { + return err + } + if len(insts) == 0 { + return nil + } + fmt.Fprintln(cmd.OutOrStdout(), "\ninstances:") + ik, _ := lookupKind("instances") + return writeTable(cmd.OutOrStdout(), insts, ik.cols) + }, + ValidArgsFunction: completeKindAndName(env, o), + } +} diff --git a/internal/cli/ops.go b/internal/cli/ops.go new file mode 100644 index 0000000..2c78e41 --- /dev/null +++ b/internal/cli/ops.go @@ -0,0 +1,219 @@ +package cli + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "strings" + + "github.com/spf13/cobra" + + "github.com/OneLiteFeatherNET/grus/internal/client" +) + +const defaultTail = 200 + +func newScaleCmd(env *Env, o *opts) *cobra.Command { + var minimum, maximum int + cmd := &cobra.Command{ + Use: "scale [--min N] [--max N]", + Short: "Change the minimum (and maximum) instance count of a pool", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + setMin, setMax := cmd.Flags().Changed("min"), cmd.Flags().Changed("max") + if !setMin && !setMax { + return errors.New("give --min and/or --max") + } + c, _, err := o.client(env) + if err != nil { + return err + } + pool, err := c.Get(cmdContext(cmd), "pools", args[0]) + if err != nil { + return err + } + spec, _ := pool["spec"].(map[string]any) + if spec == nil { + return errors.New("the controller returned a pool without spec") + } + scaling, _ := spec["scaling"].(map[string]any) + if scaling == nil { + scaling = map[string]any{} + spec["scaling"] = scaling + } + if setMin { + scaling["min"] = minimum + } + if setMax { + scaling["max"] = maximum + } + if _, err := c.Put(cmdContext(cmd), "pools", args[0], spec); err != nil { + return err + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "pool/%s scaled (min=%s max=%s)\n", args[0], + text(scaling["min"]), text(scaling["max"])) + return err + }, + ValidArgsFunction: completeFirstArg(completeResource(env, o, "pools")), + } + cmd.Flags().IntVar(&minimum, "min", 0, "minimum number of instances") + cmd.Flags().IntVar(&maximum, "max", 0, "maximum number of instances") + return cmd +} + +func newStopCmd(env *Env, o *opts) *cobra.Command { + var drain, force bool + cmd := &cobra.Command{ + Use: "stop [--drain|--force]", + Short: "Stop an instance; one with players needs --drain or --force", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if drain && force { + return errors.New("use either --drain or --force") + } + c, _, err := o.client(env) + if err != nil { + return err + } + inst, err := c.StopInstance(cmdContext(cmd), args[0], drain, force) + if err != nil { + return err + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "instance/%s %s\n", args[0], text(inst["state"])) + return err + }, + ValidArgsFunction: completeFirstArg(completeResource(env, o, "instances")), + } + cmd.Flags().BoolVar(&drain, "drain", false, "wait for the players to leave before stopping") + cmd.Flags().BoolVar(&force, "force", false, "stop now even with players on the instance") + return cmd +} + +func newLogsCmd(env *Env, o *opts) *cobra.Command { + var follow bool + var tail int + cmd := &cobra.Command{ + Use: "logs [-f] [--tail N]", + Short: "Print the log of an instance, optionally following it", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + c, _, err := o.client(env) + if err != nil { + return err + } + if follow { + return c.FollowLogs(cmdContext(cmd), args[0], func(line string) error { + _, err := fmt.Fprintln(cmd.OutOrStdout(), line) + return err + }) + } + rc, err := c.Logs(cmdContext(cmd), args[0], tail) + if err != nil { + return err + } + defer rc.Close() + _, err = io.Copy(cmd.OutOrStdout(), rc) + return err + }, + ValidArgsFunction: completeFirstArg(completeResource(env, o, "instances")), + } + cmd.Flags().BoolVarP(&follow, "follow", "f", false, "keep streaming new lines") + cmd.Flags().IntVar(&tail, "tail", defaultTail, "number of trailing lines when not following") + return cmd +} + +func newExecCmd(env *Env, o *opts) *cobra.Command { + cmd := &cobra.Command{ + Use: "exec -- ", + Short: "Send a console line to an instance", + Args: cobra.MinimumNArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + c, _, err := o.client(env) + if err != nil { + return err + } + if err := c.Command(cmdContext(cmd), args[0], strings.Join(args[1:], " ")); err != nil { + return err + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "sent to instance/%s\n", args[0]) + return err + }, + ValidArgsFunction: completeFirstArg(completeResource(env, o, "instances")), + } + return cmd +} + +func newEventsCmd(env *Env, o *opts) *cobra.Command { + var prefix, lastID string + cmd := &cobra.Command{ + Use: "events [--type prefix]", + Short: "Stream controller events until interrupted", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + c, _, err := o.client(env) + if err != nil { + return err + } + return c.Events(cmdContext(cmd), lastID, func(ev client.Event) error { + if prefix != "" && !strings.HasPrefix(ev.Type, prefix) { + return nil + } + if o.output == formatTable { + _, err := fmt.Fprintf(cmd.OutOrStdout(), "%s %s %s\n", ev.ID, ev.Type, ev.Data) + return err + } + return encodeEventLine(cmd.OutOrStdout(), o.output, ev) + }) + }, + } + cmd.Flags().StringVar(&prefix, "type", "", "only events whose type starts with this, e.g. instance.") + cmd.Flags().StringVar(&lastID, "last-id", "", "resume after this event id") + return cmd +} + +func newNetworkCmd(env *Env, o *opts) *cobra.Command { + return &cobra.Command{ + Use: "network", + Short: "Show the network-wide player count", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + c, _, err := o.client(env) + if err != nil { + return err + } + n, err := c.Network(cmdContext(cmd)) + if err != nil { + return err + } + if o.output != formatTable { + return printObject(cmd, o.output, n) + } + return printList(cmd, o.output, []object{n}, []column{ + {"PLAYERS", field("players")}, {"MAX", field("maxPlayers")}, {"PROXIES", field("proxies")}, + }) + }, + } +} + +// encodeEventLine writes one event as a compact JSON line, or as a YAML document. +func encodeEventLine(w io.Writer, format string, ev client.Event) error { + rec := map[string]any{"id": ev.ID, "type": ev.Type, "data": json.RawMessage(ev.Data)} + if format == formatYAML { + var data any + if err := json.Unmarshal(ev.Data, &data); err != nil { + data = string(ev.Data) + } + rec["data"] = data + if _, err := fmt.Fprintln(w, "---"); err != nil { + return err + } + return encode(w, formatYAML, rec) + } + b, err := json.Marshal(rec) + if err != nil { + return err + } + _, err = fmt.Fprintf(w, "%s\n", b) + return err +} diff --git a/internal/cli/output.go b/internal/cli/output.go new file mode 100644 index 0000000..a149d91 --- /dev/null +++ b/internal/cli/output.go @@ -0,0 +1,153 @@ +package cli + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "sort" + "strconv" + "strings" + "text/tabwriter" + + "github.com/spf13/cobra" + "gopkg.in/yaml.v3" + + "github.com/OneLiteFeatherNET/grus/internal/client" +) + +const ( + formatTable = "table" + formatJSON = "json" + formatYAML = "yaml" +) + +type object = client.Object + +// column is one table column: a header and how to read the cell from an object. +type column struct { + head string + get func(object) string +} + +// field reads a (nested) key path of an object as text; missing keys are empty. +func field(path ...string) func(object) string { + return func(o object) string { return text(dig(o, path...)) } +} + +func dig(o object, path ...string) any { + var cur any = o + for _, p := range path { + m, ok := cur.(map[string]any) + if !ok { + return nil + } + cur = m[p] + } + return cur +} + +// text renders a decoded JSON value as a short table cell. +func text(v any) string { + switch t := v.(type) { + case nil: + return "" + case string: + return t + case float64: + return strconv.FormatFloat(t, 'f', -1, 64) + case bool: + return strconv.FormatBool(t) + case []any: + parts := make([]string, 0, len(t)) + for _, e := range t { + parts = append(parts, text(e)) + } + return strings.Join(parts, ",") + case map[string]any: + keys := make([]string, 0, len(t)) + for k := range t { + keys = append(keys, k) + } + sort.Strings(keys) + parts := make([]string, 0, len(keys)) + for _, k := range keys { + parts = append(parts, k+"="+text(t[k])) + } + return strings.Join(parts, ",") + default: + return fmt.Sprint(t) + } +} + +// outputFormat reads the -o flag; it is validated before any command runs. +func outputFormat(cmd *cobra.Command) string { + f := cmd.Flags().Lookup("output") + if f == nil || f.Value.String() == "" { + return formatTable + } + return f.Value.String() +} + +func validFormat(f string) bool { return f == formatTable || f == formatJSON || f == formatYAML } + +// printList writes items as a table, a JSON array or a YAML list. +func printList(cmd *cobra.Command, format string, items []object, cols []column) error { + w := cmd.OutOrStdout() + switch format { + case formatJSON, formatYAML: + if items == nil { + items = []object{} + } + return encode(w, format, items) + } + if len(items) == 0 { + _, err := fmt.Fprintln(cmd.ErrOrStderr(), "No resources found.") + return err + } + return writeTable(w, items, cols) +} + +// printObject writes one object; the table format falls back to YAML because it has no sensible columns. +func printObject(cmd *cobra.Command, format string, o object) error { + if format == formatJSON { + return encode(cmd.OutOrStdout(), formatJSON, o) + } + return encode(cmd.OutOrStdout(), formatYAML, o) +} + +func writeTable(w io.Writer, items []object, cols []column) error { + tw := tabwriter.NewWriter(w, 0, 8, 3, ' ', 0) + heads := make([]string, len(cols)) + for i, c := range cols { + heads[i] = c.head + } + fmt.Fprintln(tw, strings.Join(heads, "\t")) + for _, it := range items { + cells := make([]string, len(cols)) + for i, c := range cols { + cells[i] = c.get(it) + } + fmt.Fprintln(tw, strings.Join(cells, "\t")) + } + return tw.Flush() +} + +func encode(w io.Writer, format string, v any) error { + if format == formatJSON { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetIndent("", " ") + if err := enc.Encode(v); err != nil { + return err + } + _, err := w.Write(buf.Bytes()) + return err + } + enc := yaml.NewEncoder(w) + enc.SetIndent(2) + if err := enc.Encode(v); err != nil { + return err + } + return enc.Close() +} diff --git a/internal/cli/root.go b/internal/cli/root.go new file mode 100644 index 0000000..8895c28 --- /dev/null +++ b/internal/cli/root.go @@ -0,0 +1,78 @@ +package cli + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/OneLiteFeatherNET/grus/internal/client" +) + +// opts holds the persistent flags every client command shares. +type opts struct { + context string + url string + tokenFile string + output string +} + +// NewRoot returns the root `grus` command with all client commands. The caller adds the server side +// commands (controller, fetch, ...) when it wants them. +func NewRoot(env *Env) *cobra.Command { + env.ensure() + return newRoot(env, opts{output: formatTable}, false) +} + +// newRoot builds a fresh tree; the shell calls it before every line so no flag state leaks between lines. +// defaults seed the persistent flags (the shell inherits the flags of `grus shell`). +func newRoot(env *Env, defaults opts, inShell bool) *cobra.Command { + o := defaults + root := &cobra.Command{ + Use: "grus", + Short: "Grus game server orchestration", + SilenceUsage: true, + SilenceErrors: true, + PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + if !validFormat(o.output) { + return fmt.Errorf("invalid output format %q, use table, json or yaml", o.output) + } + return nil + }, + } + pf := root.PersistentFlags() + pf.StringVar(&o.context, "context", o.context, "context from the config file to use") + pf.StringVar(&o.url, "url", o.url, "controller URL (overrides the context) [GRUS_URL]") + pf.StringVar(&o.tokenFile, "token-file", o.tokenFile, "file with the API token (token env: GRUS_TOKEN)") + pf.StringVarP(&o.output, "output", "o", o.output, "output format: table, json or yaml") + _ = root.RegisterFlagCompletionFunc("context", completeContexts(env)) + _ = root.RegisterFlagCompletionFunc("output", fixed(formatTable, formatJSON, formatYAML)) + + root.AddCommand( + newGetCmd(env, &o), newDescribeCmd(env, &o), newApplyCmd(env, &o), newScaleCmd(env, &o), + newStopCmd(env, &o), newLogsCmd(env, &o), newExecCmd(env, &o), newEventsCmd(env, &o), + newNetworkCmd(env, &o), newLoginCmd(env), newConfigCmd(env), + ) + if inShell { + root.AddCommand(newExitCmd(env)) + } else { + root.AddCommand(newShellCmd(env, &o)) + } + return root +} + +// client builds an API client for the resolved connection. +func (o *opts) client(env *Env) (*client.Client, connection, error) { + conn, err := env.resolve(o) + if err != nil { + return nil, connection{}, err + } + return client.New(conn.URL, conn.Token, env.HTTPClient), conn, nil +} + +func cmdContext(cmd *cobra.Command) context.Context { + if ctx := cmd.Context(); ctx != nil { + return ctx + } + return context.Background() +} diff --git a/internal/cli/shell.go b/internal/cli/shell.go new file mode 100644 index 0000000..5bcf74e --- /dev/null +++ b/internal/cli/shell.go @@ -0,0 +1,58 @@ +package cli + +import ( + "fmt" + "io" + "os" + "path/filepath" + + "github.com/reeflective/console" + "github.com/spf13/cobra" +) + +const historyFileName = "history" + +func newExitCmd(env *Env) *cobra.Command { + return &cobra.Command{ + Use: "exit", + Aliases: []string{"quit"}, + Short: "Leave the shell", + Args: cobra.NoArgs, + Run: func(*cobra.Command, []string) { env.Exit(0) }, + } +} + +// newShellCmd is `grus shell`: a REPL over the same command tree. The tree is rebuilt for every line, +// seeded with the flags given to `grus shell`, so a flag of one line never leaks into the next. +func newShellCmd(env *Env, o *opts) *cobra.Command { + return &cobra.Command{ + Use: "shell", + Short: "Start an interactive shell with history and live completion", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + conn, err := env.resolve(o) + if err != nil { + return err + } + seed := *o + app := console.New("grus") + menu := app.ActiveMenu() + menu.Prompt().Primary = func() string { return promptFor(conn) } + menu.SetCommands(func() *cobra.Command { return newRoot(env, seed, true) }) + menu.AddInterrupt(io.EOF, func(*console.Console) { env.Exit(0) }) + if dir, err := env.configDir(); err == nil && os.MkdirAll(dir, 0o700) == nil { + menu.AddHistorySourceFile("grus", filepath.Join(dir, historyFileName)) + } + fmt.Fprintf(cmd.ErrOrStderr(), "grus shell connected to %s, type exit or press Ctrl-D to leave\n", conn.URL) + return app.StartContext(cmdContext(cmd)) + }, + } +} + +func promptFor(conn connection) string { + name := conn.Context + if name == "" { + name = "-" + } + return "grus(" + name + ")> " +} diff --git a/internal/client/client.go b/internal/client/client.go new file mode 100644 index 0000000..33d753c --- /dev/null +++ b/internal/client/client.go @@ -0,0 +1,300 @@ +// Package client is a small typed HTTP client for the Grus REST API. It is what the grus CLI talks to. +package client + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +// requestTimeout bounds every non-streaming call. +const requestTimeout = 30 * time.Second + +// Object is a decoded API resource. The CLI keeps resources generic so fields added by newer +// controllers show up without a client change. +type Object = map[string]any + +// optional lists the resources an older controller may not serve; a 404 on them means "not supported". +var optional = map[string]bool{"groups": true, "environments": true, "hosts": true} + +// APIError is an error answer of the controller (RFC 9457 problem document). +type APIError struct { + Status int + Title string + Detail string + Errors []string +} + +func (e *APIError) Error() string { + msg := e.Detail + if msg == "" { + msg = e.Title + } + if msg == "" { + msg = http.StatusText(e.Status) + } + if len(e.Errors) > 0 { + msg += ": " + strings.Join(e.Errors, "; ") + } + switch e.Status { + case http.StatusUnauthorized, http.StatusForbidden: + msg += " (check the token, see grus login)" + } + return fmt.Sprintf("controller answered %d: %s", e.Status, msg) +} + +// NotSupportedError means the controller does not serve the endpoint (it answered 404 for a list route). +type NotSupportedError struct{ What string } + +func (e *NotSupportedError) Error() string { return e.What + " is not supported by this controller" } + +// Client talks to one controller. +type Client struct { + base string + token string + http *http.Client +} + +// New returns a client for the controller at base. A nil hc uses a client without an overall timeout; +// non-streaming calls are bounded by a context deadline instead. +func New(base, token string, hc *http.Client) *Client { + if hc == nil { + hc = &http.Client{} + } + return &Client{base: strings.TrimRight(base, "/"), token: token, http: hc} +} + +func (c *Client) newRequest(ctx context.Context, method, path string, query url.Values, body any) (*http.Request, error) { + var rdr io.Reader + if body != nil { + b, err := json.Marshal(body) + if err != nil { + return nil, err + } + rdr = bytes.NewReader(b) + } + u := c.base + path + if len(query) > 0 { + u += "?" + query.Encode() + } + req, err := http.NewRequestWithContext(ctx, method, u, rdr) + if err != nil { + return nil, err + } + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + return req, nil +} + +// send performs the request and returns the response; a status >= 400 becomes an *APIError. +func (c *Client) send(req *http.Request) (*http.Response, error) { + resp, err := c.http.Do(req) + if err != nil { + return nil, err + } + if resp.StatusCode >= 400 { + defer resp.Body.Close() + return nil, decodeProblem(resp) + } + return resp, nil +} + +func decodeProblem(resp *http.Response) error { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + var p struct { + Title string `json:"title"` + Detail string `json:"detail"` + Errors []struct { + Message string `json:"message"` + Location string `json:"location"` + } `json:"errors"` + } + e := &APIError{Status: resp.StatusCode} + if json.Unmarshal(raw, &p) == nil { + e.Title, e.Detail = p.Title, p.Detail + for _, d := range p.Errors { + if d.Location != "" { + e.Errors = append(e.Errors, d.Location+": "+d.Message) + } else { + e.Errors = append(e.Errors, d.Message) + } + } + } + return e +} + +// call is a bounded JSON round trip; out may be nil. +func (c *Client) call(ctx context.Context, method, path string, query url.Values, body, out any) error { + ctx, cancel := context.WithTimeout(ctx, requestTimeout) + defer cancel() + req, err := c.newRequest(ctx, method, path, query, body) + if err != nil { + return err + } + resp, err := c.send(req) + if err != nil { + return err + } + defer resp.Body.Close() + if out == nil || resp.StatusCode == http.StatusNoContent { + _, _ = io.Copy(io.Discard, resp.Body) + return nil + } + return json.NewDecoder(resp.Body).Decode(out) +} + +func isStatus(err error, codes ...int) bool { + var ae *APIError + if !errors.As(err, &ae) { + return false + } + for _, c := range codes { + if ae.Status == c { + return true + } + } + return false +} + +// List returns every object of a resource: pools, instances, groups, environments or hosts. +// Instances accept the filters pool, state and role in query. +func (c *Client) List(ctx context.Context, resource string, query url.Values) ([]Object, error) { + var out []Object + err := c.call(ctx, http.MethodGet, "/v1/"+resource, query, nil, &out) + if err != nil { + if optional[resource] && isStatus(err, http.StatusNotFound) { + return nil, &NotSupportedError{What: resource} + } + return nil, err + } + return out, nil +} + +// Get returns one object by name (for instances: by id). +func (c *Client) Get(ctx context.Context, resource, name string) (Object, error) { + var out Object + err := c.call(ctx, http.MethodGet, "/v1/"+resource+"/"+url.PathEscape(name), nil, nil, &out) + if err != nil && optional[resource] && isStatus(err, http.StatusNotFound) { + // A 404 is either an unknown name or a missing route; the list route tells them apart. + if _, lerr := c.List(ctx, resource, nil); lerr != nil { + var ns *NotSupportedError + if errors.As(lerr, &ns) { + return nil, lerr + } + } + } + return out, err +} + +// Put creates or replaces a pool, group or environment from its spec. +func (c *Client) Put(ctx context.Context, resource, name string, spec any) (Object, error) { + var out Object + err := c.call(ctx, http.MethodPut, "/v1/"+resource+"/"+url.PathEscape(name), nil, spec, &out) + if err != nil && optional[resource] && isStatus(err, http.StatusNotFound, http.StatusMethodNotAllowed) { + return nil, &NotSupportedError{What: resource} + } + return out, err +} + +// Templates returns template name -> tag -> digest. +func (c *Client) Templates(ctx context.Context) (map[string]map[string]string, error) { + var out map[string]map[string]string + err := c.call(ctx, http.MethodGet, "/v1/templates", nil, nil, &out) + return out, err +} + +// Network returns the network-wide player count. +func (c *Client) Network(ctx context.Context) (Object, error) { + var out Object + err := c.call(ctx, http.MethodGet, "/v1/network", nil, nil, &out) + if err != nil && isStatus(err, http.StatusNotFound) { + return nil, &NotSupportedError{What: "network"} + } + return out, err +} + +// StopInstance stops an instance. With players on it the controller needs drain or force. +func (c *Client) StopInstance(ctx context.Context, id string, drain, force bool) (Object, error) { + var body any + if drain || force { + body = map[string]bool{"drain": drain, "force": force} + } + var out Object + err := c.call(ctx, http.MethodPost, "/v1/instances/"+url.PathEscape(id)+"/stop", nil, body, &out) + return out, err +} + +// Command sends one console line to an instance. +func (c *Client) Command(ctx context.Context, id, line string) error { + return c.call(ctx, http.MethodPost, "/v1/instances/"+url.PathEscape(id)+"/command", nil, + map[string]string{"line": line}, nil) +} + +// Logs returns the last tail lines of an instance log as text. The caller closes the reader. +func (c *Client) Logs(ctx context.Context, id string, tail int) (io.ReadCloser, error) { + q := url.Values{} + if tail > 0 { + q.Set("tail", fmt.Sprint(tail)) + } + req, err := c.newRequest(ctx, http.MethodGet, "/v1/instances/"+url.PathEscape(id)+"/logs", q, nil) + if err != nil { + return nil, err + } + resp, err := c.send(req) + if err != nil { + return nil, err + } + return resp.Body, nil +} + +// FollowLogs streams the log of an instance and calls fn for every line until ctx ends or the stream closes. +func (c *Client) FollowLogs(ctx context.Context, id string, fn func(line string) error) error { + return c.stream(ctx, "/v1/instances/"+url.PathEscape(id)+"/logs/stream", "", func(ev Event) error { + return fn(string(ev.Data)) + }) +} + +// Event is one server-sent event of GET /v1/events. +type Event struct { + ID string + Type string + Data json.RawMessage +} + +// Events streams the controller events and calls fn for each until ctx ends or the stream closes. +// lastID resumes after that event id when not empty. +func (c *Client) Events(ctx context.Context, lastID string, fn func(Event) error) error { + return c.stream(ctx, "/v1/events", lastID, fn) +} + +func (c *Client) stream(ctx context.Context, path, lastID string, fn func(Event) error) error { + req, err := c.newRequest(ctx, http.MethodGet, path, nil, nil) + if err != nil { + return err + } + req.Header.Set("Accept", "text/event-stream") + if lastID != "" { + req.Header.Set("Last-Event-ID", lastID) + } + resp, err := c.send(req) + if err != nil { + return err + } + defer resp.Body.Close() + err = ReadSSE(resp.Body, fn) + if ctx.Err() != nil { + return nil + } + return err +} diff --git a/internal/client/client_test.go b/internal/client/client_test.go new file mode 100644 index 0000000..0c974c9 --- /dev/null +++ b/internal/client/client_test.go @@ -0,0 +1,194 @@ +package client + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func newTestClient(t *testing.T, h http.Handler) *Client { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + return New(srv.URL, "secret", srv.Client()) +} + +func TestListSendsBearerTokenAndQuery(t *testing.T) { + var gotAuth, gotQuery string + c := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth, gotQuery = r.Header.Get("Authorization"), r.URL.RawQuery + _, _ = w.Write([]byte(`[{"id":"a"}]`)) + })) + got, err := c.List(context.Background(), "instances", map[string][]string{"pool": {"lobby"}}) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0]["id"] != "a" { + t.Errorf("List = %v", got) + } + if gotAuth != "Bearer secret" { + t.Errorf("Authorization = %q", gotAuth) + } + if gotQuery != "pool=lobby" { + t.Errorf("query = %q", gotQuery) + } +} + +func TestProblemDocumentBecomesAPIError(t *testing.T) { + c := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(http.StatusUnprocessableEntity) + _, _ = w.Write([]byte(`{"title":"Unprocessable","detail":"invalid spec","errors":[{"message":"must be >= 0","location":"body.scaling.min"}]}`)) + })) + _, err := c.Put(context.Background(), "pools", "lobby", map[string]any{}) + var ae *APIError + if !errors.As(err, &ae) || ae.Status != 422 { + t.Fatalf("err = %v, want APIError 422", err) + } + if !strings.Contains(err.Error(), "body.scaling.min: must be >= 0") { + t.Errorf("message = %q lacks the field error", err) + } +} + +func TestMissingOptionalListIsNotSupported(t *testing.T) { + c := newTestClient(t, http.NotFoundHandler()) + for _, res := range []string{"groups", "environments", "hosts"} { + _, err := c.List(context.Background(), res, nil) + var ns *NotSupportedError + if !errors.As(err, &ns) { + t.Errorf("List(%s) err = %v, want NotSupportedError", res, err) + } + } + _, err := c.Network(context.Background()) + var ns *NotSupportedError + if !errors.As(err, &ns) || !strings.Contains(err.Error(), "not supported by this controller") { + t.Errorf("Network err = %v", err) + } +} + +func TestMissingPoolIsPlainNotFound(t *testing.T) { + c := newTestClient(t, http.NotFoundHandler()) + _, err := c.List(context.Background(), "pools", nil) + var ns *NotSupportedError + if errors.As(err, &ns) { + t.Fatalf("pools must never be reported as unsupported: %v", err) + } +} + +func TestGetUnknownGroupOnSupportingControllerIsNotFound(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /v1/groups", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`[]`)) }) + c := newTestClient(t, mux) + _, err := c.Get(context.Background(), "groups", "nope") + var ns *NotSupportedError + if errors.As(err, &ns) || !isStatus(err, 404) { + t.Fatalf("err = %v, want plain 404", err) + } +} + +func TestPutGroupOnOldControllerIsNotSupported(t *testing.T) { + c := newTestClient(t, http.NotFoundHandler()) + _, err := c.Put(context.Background(), "groups", "g", map[string]any{}) + var ns *NotSupportedError + if !errors.As(err, &ns) { + t.Fatalf("err = %v, want NotSupportedError", err) + } +} + +func TestStopSendsOptionsOnlyWhenSet(t *testing.T) { + var bodies []string + c := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + bodies = append(bodies, string(b)) + _, _ = w.Write([]byte(`{"id":"i-1"}`)) + })) + if _, err := c.StopInstance(context.Background(), "i-1", false, false); err != nil { + t.Fatal(err) + } + if _, err := c.StopInstance(context.Background(), "i-1", true, false); err != nil { + t.Fatal(err) + } + if bodies[0] != "" || !strings.Contains(bodies[1], `"drain":true`) { + t.Errorf("bodies = %q", bodies) + } +} + +func TestCommandPostsLine(t *testing.T) { + var got string + c := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + got = r.URL.Path + " " + string(b) + w.WriteHeader(http.StatusNoContent) + })) + if err := c.Command(context.Background(), "i-1", "say hi"); err != nil { + t.Fatal(err) + } + if got != `/v1/instances/i-1/command {"line":"say hi"}` { + t.Errorf("got %q", got) + } +} + +func TestLogsReturnsText(t *testing.T) { + var q string + c := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q = r.URL.RawQuery + _, _ = w.Write([]byte("line1\nline2\n")) + })) + rc, err := c.Logs(context.Background(), "i-1", 50) + if err != nil { + t.Fatal(err) + } + defer rc.Close() + b, _ := io.ReadAll(rc) + if string(b) != "line1\nline2\n" || q != "tail=50" { + t.Errorf("body = %q query = %q", b, q) + } +} + +func TestFollowLogsDeliversEveryDataLine(t *testing.T) { + c := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: first\n\ndata: second\n\n") + })) + var lines []string + err := c.FollowLogs(context.Background(), "i-1", func(l string) error { lines = append(lines, l); return nil }) + if err != nil { + t.Fatal(err) + } + if strings.Join(lines, "|") != "first|second" { + t.Errorf("lines = %v", lines) + } +} + +func TestEventsParsesIDTypeAndResumes(t *testing.T) { + var last string + c := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + last = r.Header.Get("Last-Event-ID") + _, _ = io.WriteString(w, ": hello\n\nid: 1-2\nevent: pool.updated\ndata: {\"pool\":\"lobby\"}\n\n") + })) + var got []Event + err := c.Events(context.Background(), "1-1", func(e Event) error { got = append(got, e); return nil }) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0].ID != "1-2" || got[0].Type != "pool.updated" || string(got[0].Data) != `{"pool":"lobby"}` { + t.Errorf("events = %+v", got) + } + if last != "1-1" { + t.Errorf("Last-Event-ID = %q", last) + } +} + +func TestTemplates(t *testing.T) { + c := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"paper":{"stable":"sha256:ab"}}`)) + })) + got, err := c.Templates(context.Background()) + if err != nil || got["paper"]["stable"] != "sha256:ab" { + t.Errorf("got %v err %v", got, err) + } +} diff --git a/internal/client/sse.go b/internal/client/sse.go new file mode 100644 index 0000000..2696a50 --- /dev/null +++ b/internal/client/sse.go @@ -0,0 +1,51 @@ +package client + +import ( + "bufio" + "io" + "strings" +) + +// maxSSELine bounds one SSE line; event payloads are small JSON documents. +const maxSSELine = 1 << 20 + +// ReadSSE parses a text/event-stream and calls fn for every dispatched event. Comment lines are skipped. +func ReadSSE(r io.Reader, fn func(Event) error) error { + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 0, 64*1024), maxSSELine) + var ev Event + var data []string + flush := func() error { + if len(data) == 0 && ev.Type == "" { + ev = Event{} + return nil + } + ev.Data = []byte(strings.Join(data, "\n")) + out := ev + ev, data = Event{}, nil + return fn(out) + } + for sc.Scan() { + line := sc.Text() + if line == "" { + if err := flush(); err != nil { + return err + } + continue + } + if strings.HasPrefix(line, ":") { + continue + } + field, value, _ := strings.Cut(line, ":") + value = strings.TrimPrefix(value, " ") + switch field { + case "id": + ev.ID = value + case "event": + ev.Type = value + case "data": + data = append(data, value) + } + } + return sc.Err() +}