diff --git a/CLAUDE.md b/CLAUDE.md index a8f81bea..03f58694 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,6 +50,7 @@ Each command directory has its own `CLAUDE.md` (domain knowledge) and `README.md | `cmd/update/` | CLAUDE.md, README.md | CLI self-update | | `cmd/settings/` | CLAUDE.md, README.md | CLI settings management | | `cmd/objectstorage/` | CLAUDE.md, README.md | S3-style object storage: configure, mb/rb, cp/mv/sync/ls/rm, uploads, presign | +| `cmd/network/` | CLAUDE.md, README.md | Private networks (beta): list, create, delete; subnet list, create, delete | | `cmd/serverless/` | CLAUDE.md, README.md | Serverless containers (beta: create, list, describe, scale, replicas, pause/resume/restart, purge-queue, delete) and batch jobs (hidden, gated by `VERDA_BATCHJOB_ENABLED`) | | `cmd/doctor/` | — | Environment diagnostics | | `cmd/availability/` | — | Instance availability by location | diff --git a/go.mod b/go.mod index dd791670..e62b7b8a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/verda-cloud/verda-cli -go 1.26.10 +go 1.26.11 require ( charm.land/lipgloss/v2 v2.0.2 @@ -8,8 +8,8 @@ require ( github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 github.com/spf13/viper v1.21.0 - github.com/verda-cloud/verdacloud-sdk-go v1.7.1 - go.yaml.in/yaml/v3 v3.0.4 + github.com/verda-cloud/verdacloud-sdk-go v1.9.0 + go.yaml.in/yaml/v3 v3.0.5 ) require ( @@ -93,13 +93,14 @@ require ( github.com/yosida95/uritemplate/v3 v3.0.2 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect - go.opentelemetry.io/otel v1.45.0 // indirect - go.opentelemetry.io/otel/metric v1.45.0 // indirect - go.opentelemetry.io/otel/sdk v1.45.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.45.0 // indirect - go.opentelemetry.io/otel/trace v1.45.0 // indirect + go.opentelemetry.io/otel v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/otel/metric v1.47.0 // indirect + go.opentelemetry.io/otel/sdk v1.47.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.47.0 // indirect + go.opentelemetry.io/otel/trace v1.47.0 // indirect go.uber.org/multierr v1.10.0 // indirect golang.org/x/sync v0.22.0 // indirect - golang.org/x/sys v0.47.0 // indirect + golang.org/x/sys v0.48.0 // indirect golang.org/x/text v0.41.0 // indirect ) diff --git a/go.sum b/go.sum index 0b4fbb21..180431ff 100644 --- a/go.sum +++ b/go.sum @@ -82,7 +82,6 @@ github.com/containerd/stargz-snapshotter/estargz v0.18.2 h1:yXkZFYIzz3eoLwlTUZKz github.com/containerd/stargz-snapshotter/estargz v0.18.2/go.mod h1:XyVU5tcJ3PRpkA9XS2T5us6Eg35yM0214Y+wvrZTBrY= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= @@ -149,7 +148,6 @@ github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJw github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= @@ -181,14 +179,15 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/vbatts/tar-split v0.12.2 h1:w/Y6tjxpeiFMR47yzZPlPj/FcPLpXbTUi/9H7d3CPa4= github.com/vbatts/tar-split v0.12.2/go.mod h1:eF6B6i6ftWQcDqEn3/iGFRFRo8cBIMSJVOpnNdfTMFA= -github.com/verda-cloud/verdacloud-sdk-go v1.7.1 h1:rgYBNMWSJ9IZsZspdQF0TvWBXB2Td2v00d07TJqstCA= -github.com/verda-cloud/verdacloud-sdk-go v1.7.1/go.mod h1:1APG3X5TXhXpUp1dhgemElaj/6bw+OaKeQ+Ze/0/Cyc= +github.com/verda-cloud/verdacloud-sdk-go v1.9.0 h1:uKFMwgpHRheKurx0ANhxAsUe21znJn68ndN/MkpH/SQ= +github.com/verda-cloud/verdacloud-sdk-go v1.9.0/go.mod h1:va7s1wnZpFCqY/WVFxuUb66FpJzXgqHBYEWtEJTWx8o= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= @@ -197,39 +196,40 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= -go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= -go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= -go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= -go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= -go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= -go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= -go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= -go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= -go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= +go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= +go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/ini.v1 v1.67.1 h1:tVBILHy0R6e4wkYOn3XmiITt/hEVH4TFMYvAX2Ytz6k= gopkg.in/ini.v1 v1.67.1/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/internal/verda-cli/cmd/cmd.go b/internal/verda-cli/cmd/cmd.go index efaa0641..57dc728c 100644 --- a/internal/verda-cli/cmd/cmd.go +++ b/internal/verda-cli/cmd/cmd.go @@ -35,6 +35,7 @@ import ( "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/instancetypes" "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/locations" mcpcmd "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/mcp" + "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/network" "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/objectstorage" "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/registry" "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/serverless" @@ -135,6 +136,7 @@ func NewRootCommand(ioStreams cmdutil.IOStreams) (*cobra.Command, *clioptions.Op images.NewCmdImages(f, ioStreams), instancetypes.NewCmdInstanceTypes(f, ioStreams), locations.NewCmdLocations(f, ioStreams), + network.NewCmdNetwork(f, ioStreams), registry.NewCmdRegistry(f, ioStreams), objectstorage.NewCmdObjectStorage(f, ioStreams), sshkey.NewCmdSSHKey(f, ioStreams), diff --git a/internal/verda-cli/cmd/network/CLAUDE.md b/internal/verda-cli/cmd/network/CLAUDE.md new file mode 100644 index 00000000..b88751e5 --- /dev/null +++ b/internal/verda-cli/cmd/network/CLAUDE.md @@ -0,0 +1,35 @@ +# Network Command Knowledge + +> Go house style lives in the root `CLAUDE.md` § "Go House Style". This file carries private-network idioms only. + +## Quick Reference + +- Parent: `verda network` (aliases `networks`, `net`, `private-network`, `vpc`), tagged `(beta)` via `cmdutil.TagAnnotation`, registered under "Resource Commands:" in `cmd/cmd.go`. +- Verbs: `list` (`ls`), `create`, `delete` (`rm`); `subnet` (`subnets`) with `list` (`ls`), `create` and `delete` (`rm`). +- SDK: `client.PrivateNetworks` (experimental in the SDK). +- Files: one per verb; `cidr.go` (free /24), `views.go` (JSON/YAML shapes), `wizard.go` (create flows); tests use the in-memory API in `fake_test.go`. + +## Domain-Specific Logic + +- **A network is global; a subnet is per location.** Network names are unique in a project. +- **Default network.** A VM that does not name a network joins the default network. `create --default` makes the new network the default. +- **Mode.** `custom` (default): the user creates the subnets. `auto`: only for the project's default network, a deploy that names no subnet makes the API create one in its location, from the location's `private_network_auto_subnet` range. A deploy that names a non-default auto network gets a 400 if the location has no subnet. +- **Names** are trimmed on every path (flag and wizard) and limited to 64 characters, counted in runes, not bytes. +- **IDs only.** Arguments and `--network` take IDs, never names. `delete` reads the network with `GetByID`; `subnet delete` needs `--network` and reads the subnet with `GetSubnetByID`. An unknown ID is the API 404, which `ClassifyError` reports as `NOT_FOUND`. `subnet list` and `subnet create` match `--network` against the network list and return `NOT_FOUND` themselves. Subnet names are unique in a network: `subnet create` checks a new name against them. +- **Delete with instances: the API refuses (409) and changes nothing.** The CLI does not check first; `ClassifyError` reports the 409 as `API_ERROR` (exit 4). It never deletes instances. +- **Network delete removes its subnets.** The confirmation lists them (one extra `GetSubnets` call, skipped with `--yes`). +- **`is_default` on network create is only sent when true** (`CreatePrivateNetworkRequest.IsDefault` is `omitempty`); the test checks the exact body. +- **`is_default` on subnet create is a `*bool`.** The CLI sets it only when the user sets `--default` or answers the wizard step. `--default=false` sends `false`, and the API keeps it. With nil, the API makes the new subnet the default when the network has no default subnet in that location: no subnets yet, only `false` subnets, or the default was deleted (the API does not move the default on delete). The OpenAPI text ("the first subnet in a datacenter") is wrong; a production run confirmed this rule. For that reason, the wizard skips the step when the location has no default subnet, unless `--default` was given (a skipped step resets its value). +- **Subnet CIDR.** `freeSubnetCIDR` suggests the first free /24 in 10.0.0.0/16. The CLI does not check `--cidr`: the API decides which ranges it accepts. With `--network`, the command reads only that network's subnets. +- **Subnet locations.** Only locations with `IsPrivateNetworksEnabled`. Another location gives `VALIDATION_ERROR` that lists the allowed codes. + +## Gotchas & Edge Cases + +- **AgentErrors print as JSON outside agent mode too** (`main.go`): `create` without `--name`, `subnet create` without `--network` / `--location`, `delete` without a target, or `subnet delete` without a target or `--network`, on a pipe gives the `MISSING_REQUIRED_FLAGS` envelope with exit 2. +- **Agent mode without `--yes`** fails with `CONFIRMATION_REQUIRED` before any API call, for both deletes. +- **Pickers** run only on a terminal, outside agent mode, with table output. The `subnet delete` picker lists the subnets of `--network` when given, else of all networks. Cancel (the last row, Esc, Ctrl+C) prints `Canceled.` to stderr and exits cleanly, like a declined confirmation. + +## Relationships + +- `cmdutil` — `WithSpinner`, `RunWithSpinner`, `DebugJSON`, `WriteStructured`, `TimeColumn`, `TextColumn`, `NewMissingFlagsError`, `NewValidationError`, `NewConfirmationRequiredError`. +- `pkg/tui/wizard` — the create flows. diff --git a/internal/verda-cli/cmd/network/README.md b/internal/verda-cli/cmd/network/README.md new file mode 100644 index 00000000..6ecfd5b3 --- /dev/null +++ b/internal/verda-cli/cmd/network/README.md @@ -0,0 +1,21 @@ +# verda network -- Manage private networks (beta) + +Commands, flags and behavior: `verda network --help` and `verda network --help`. Commands take IDs, not names. + +## Workflow + +```bash +NETWORK_ID=$(verda network create --name prod -o json | jq -r .id) +SUBNET_ID=$(verda network subnet create --network "$NETWORK_ID" -l FIN-03 -o json | jq -r .id) +verda network subnet list --network "$NETWORK_ID" +verda network subnet delete "$SUBNET_ID" --network "$NETWORK_ID" +verda network delete "$NETWORK_ID" +``` + +## Agent Mode + +- Missing `--name`, `--network`, `--location` or an ID: `MISSING_REQUIRED_FLAGS` (exit 2). +- Bad input (mode, name, location): `VALIDATION_ERROR` (exit 2), before the create request. The API checks `--cidr`. +- Delete without `--yes`: `CONFIRMATION_REQUIRED` (exit 2). +- Unknown ID: `NOT_FOUND` (exit 5). +- Delete success: `{"resource", "id", "name", "action": "delete", "status": "completed"}`. diff --git a/internal/verda-cli/cmd/network/cidr.go b/internal/verda-cli/cmd/network/cidr.go new file mode 100644 index 00000000..7ba84a46 --- /dev/null +++ b/internal/verda-cli/cmd/network/cidr.go @@ -0,0 +1,73 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "fmt" + "net/netip" + "slices" + + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" +) + +// defaultSubnetPool is where freeSubnetCIDR looks for a subnet range. +var defaultSubnetPool = netip.MustParsePrefix("10.0.0.0/16") + +// defaultSubnetBits is the size of a suggested subnet (/24). +const defaultSubnetBits = 24 + +// checkCIDRFormat checks only that s is an IPv4 prefix, as the SDK does. +// The API decides which ranges it accepts. +func checkCIDRFormat(s string) error { + if p, err := netip.ParsePrefix(s); err != nil || !p.Addr().Is4() { + return fmt.Errorf("%q is not an IPv4 CIDR (example: 10.0.1.0/24)", s) + } + return nil +} + +// freeSubnetCIDR returns the first /24 in 10.0.0.0/16 that overlaps none of taken. +func freeSubnetCIDR(taken []netip.Prefix) (netip.Prefix, error) { + for a := defaultSubnetPool.Addr(); defaultSubnetPool.Contains(a); { + block := netip.PrefixFrom(a, defaultSubnetBits) + if !slices.ContainsFunc(taken, block.Overlaps) { + return block, nil + } + for block.Contains(a) { + a = a.Next() + } + } + return netip.Prefix{}, fmt.Errorf("no free subnet range: every /%d in %s is taken", defaultSubnetBits, defaultSubnetPool) +} + +// subnetPrefixes skips subnets whose CIDR does not parse. +func subnetPrefixes(subnets []verda.Subnet) []netip.Prefix { + out := make([]netip.Prefix, 0, len(subnets)) + for i := range subnets { + if p, err := netip.ParsePrefix(subnets[i].CIDR); err == nil { + out = append(out, p) + } + } + return out +} + +// defaultNetwork returns nil when no network is the default; it never falls back to another network. +func defaultNetwork(networks []verda.PrivateNetwork) *verda.PrivateNetwork { + for i := range networks { + if networks[i].IsDefault { + return &networks[i] + } + } + return nil +} diff --git a/internal/verda-cli/cmd/network/cidr_test.go b/internal/verda-cli/cmd/network/cidr_test.go new file mode 100644 index 00000000..9a282759 --- /dev/null +++ b/internal/verda-cli/cmd/network/cidr_test.go @@ -0,0 +1,67 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "net/netip" + "testing" +) + +func prefixes(t *testing.T, ss ...string) []netip.Prefix { + t.Helper() + out := make([]netip.Prefix, len(ss)) + for i, s := range ss { + out[i] = netip.MustParsePrefix(s) + } + return out +} + +func TestFreeSubnetCIDR(t *testing.T) { + t.Parallel() + tests := []struct { + name string + taken []string + want string + wantErr bool + }{ + {name: "empty network", want: "10.0.0.0/24"}, + {name: "first taken", taken: []string{"10.0.0.0/24"}, want: "10.0.1.0/24"}, + {name: "gap between subnets", taken: []string{"10.0.0.0/24", "10.0.2.0/24"}, want: "10.0.1.0/24"}, + {name: "larger subnet covers several blocks", taken: []string{"10.0.0.0/22"}, want: "10.0.4.0/24"}, + {name: "small subnet blocks its /24", taken: []string{"10.0.0.8/29"}, want: "10.0.1.0/24"}, + {name: "subnet outside the pool is ignored", taken: []string{"172.16.0.0/24"}, want: "10.0.0.0/24"}, + {name: "supernet of the pool", taken: []string{"10.0.0.0/8"}, wantErr: true}, + {name: "full range", taken: []string{"10.0.0.0/17", "10.0.128.0/17"}, wantErr: true}, + {name: "IPv6 taken is ignored", taken: []string{"fd00::/64"}, want: "10.0.0.0/24"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got, err := freeSubnetCIDR(prefixes(t, tt.taken...)) + if tt.wantErr { + if err == nil { + t.Fatalf("want error, got %s", got) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got.String() != tt.want { + t.Errorf("got %s, want %s", got, tt.want) + } + }) + } +} diff --git a/internal/verda-cli/cmd/network/create.go b/internal/verda-cli/cmd/network/create.go new file mode 100644 index 00000000..e4523a81 --- /dev/null +++ b/internal/verda-cli/cmd/network/create.go @@ -0,0 +1,127 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "fmt" + "strings" + + "github.com/spf13/cobra" + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + "github.com/verda-cloud/verda-cli/pkg/tui/wizard" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +const flagMode = "mode" + +type createOptions struct { + Name string + Mode string + Default bool + modeSet bool + defaultSet bool +} + +// NewCmdCreate creates the network create command. +func NewCmdCreate(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command { + opts := &createOptions{Mode: verda.NetworkModeCustom} + cmd := &cobra.Command{ + Use: "create", + Short: "Create a private network", + Long: cmdutil.LongDesc(` + Create a private network. On a terminal without --name, the + CLI asks for the name and for each value that you do not + give. In scripts and agent mode, --name is necessary. + + Mode "custom" (the default) means you create the subnets. + Mode "auto" matters only for the default network: a deploy + that names no subnet gets one in its location, from that + location's range. Otherwise, create the subnets yourself. + --default makes the new network the one VMs join when they + name no network. + `), + Example: cmdutil.Examples(` + verda network create + verda network create --name prod + verda network create --name staging --mode auto --default + `), + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + opts.modeSet = cmd.Flags().Changed(flagMode) + opts.defaultSet = cmd.Flags().Changed(flagDefault) + return runCreate(cmd, f, ioStreams, opts) + }, + } + flags := cmd.Flags() + flags.StringVar(&opts.Name, flagName, "", "Network name (1-64 characters, unique in the project)") + flags.StringVar(&opts.Mode, flagMode, verda.NetworkModeCustom, "Subnet mode: custom or auto") + flags.BoolVar(&opts.Default, flagDefault, false, "Make this the default network") + return cmd +} + +func runCreate(cmd *cobra.Command, f cmdutil.Factory, ioStreams cmdutil.IOStreams, opts *createOptions) error { + opts.Name = strings.TrimSpace(opts.Name) + opts.Mode = strings.ToLower(strings.TrimSpace(opts.Mode)) + if opts.Mode != verda.NetworkModeCustom && opts.Mode != verda.NetworkModeAuto { + return cmdutil.NewValidationError("mode", "must be custom or auto") + } + if opts.Name == "" { + if !interactiveTTY(f) { + return cmdutil.NewMissingFlagsError([]string{"--" + flagName}) + } + engine := wizard.NewEngine(f.Prompter(), f.Status(), wizard.WithOutput(ioStreams.ErrOut)) + if err := engine.Run(cmd.Context(), buildNetworkCreateFlow(opts)); err != nil { + return err + } + } + if err := validateName(opts.Name); err != nil { + return cmdutil.NewValidationError("name", err.Error()) + } + + client, err := f.VerdaClient() + if err != nil { + return err + } + req := verda.CreatePrivateNetworkRequest{Name: opts.Name, Mode: opts.Mode, IsDefault: opts.Default} + cmdutil.DebugJSON(ioStreams.ErrOut, f.Debug(), "Request payload:", req) + + ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) + defer cancel() + network, err := cmdutil.WithSpinner(ctx, f.Status(), "Creating private network...", func(ctx context.Context) (*verda.PrivateNetwork, error) { + return client.PrivateNetworks.Create(ctx, req) + }) + if err != nil { + return err + } + cmdutil.DebugJSON(ioStreams.ErrOut, f.Debug(), "API response:", network) + + view := newNetworkView(network) + if wrote, err := cmdutil.WriteStructured(ioStreams.Out, f.OutputFormat(), view); wrote { + return err + } + _, _ = fmt.Fprintf(ioStreams.Out, "Created private network %s (%s), mode %s", view.Name, view.ID, view.Mode) + if view.IsDefault { + _, _ = fmt.Fprint(ioStreams.Out, ", default") + } + _, _ = fmt.Fprintln(ioStreams.Out) + // Auto mode creates subnets only for the default network. + if view.Mode == verda.NetworkModeCustom || !view.IsDefault { + _, _ = fmt.Fprintln(ioStreams.ErrOut, "Next: verda network subnet create --network "+view.ID) + } + return nil +} diff --git a/internal/verda-cli/cmd/network/create_test.go b/internal/verda-cli/cmd/network/create_test.go new file mode 100644 index 00000000..a129ed61 --- /dev/null +++ b/internal/verda-cli/cmd/network/create_test.go @@ -0,0 +1,156 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "encoding/json" + "io" + "strings" + "testing" + + "github.com/verda-cloud/verda-cli/pkg/tui/wizard" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +func TestCreateFlowCollectsAllSteps(t *testing.T) { + t.Parallel() + opts := &createOptions{Mode: "custom"} + engine := wizard.NewEngine(nil, nil, wizard.WithOutput(io.Discard), wizard.WithTestResults( + wizard.TextResult("prod"), + wizard.SelectResult(1), + wizard.ConfirmResult(true), + )) + if err := engine.Run(context.Background(), buildNetworkCreateFlow(opts)); err != nil { + t.Fatalf("run: %v", err) + } + if opts.Name != "prod" || opts.Mode != "auto" || !opts.Default { + t.Errorf("opts = %+v", opts) + } +} + +func TestCreateFlowSkipsStepsSetByFlags(t *testing.T) { + t.Parallel() + opts := &createOptions{Mode: "auto", modeSet: true, defaultSet: true} + engine := wizard.NewEngine(nil, nil, wizard.WithOutput(io.Discard), wizard.WithTestResults( + wizard.TextResult("only-name"), + )) + if err := engine.Run(context.Background(), buildNetworkCreateFlow(opts)); err != nil { + t.Fatalf("run: %v", err) + } + if opts.Name != "only-name" || opts.Mode != "auto" || opts.Default { + t.Errorf("opts = %+v", opts) + } +} + +func TestCreateFlagsRequestBody(t *testing.T) { + t.Parallel() + api := newFakeAPI() + client := newFakeClient(t, api) + out, _, err := runNetwork(t, agentFactory(client), "create", "--name", "prod") + if err != nil { + t.Fatalf("create: %v", err) + } + posts := api.requestsMatching("POST") + if len(posts) != 1 { + t.Fatalf("want 1 POST, got %v", posts) + } + var body map[string]any + _ = json.Unmarshal([]byte(posts[0].Body), &body) + if body["name"] != "prod" || body["mode"] != "custom" { + t.Errorf("body = %s", posts[0].Body) + } + if _, ok := body["is_default"]; ok { + t.Errorf("is_default must be absent without --default: %s", posts[0].Body) + } + var view map[string]any + if err := json.Unmarshal([]byte(out), &view); err != nil || view["name"] != "prod" { + t.Errorf("stdout = %s (err %v)", out, err) + } +} + +func TestCreateCustomPrintsSubnetHint(t *testing.T) { + t.Parallel() + client := newFakeClient(t, newFakeAPI()) + _, errOut, err := runNetwork(t, tableFactory(client, nil), "create", "--name", "prod") + if err != nil || !strings.Contains(errOut, "Next: verda network subnet create --network pn_new1") { + t.Errorf("stderr = %q, err = %v", errOut, err) + } +} + +func TestCreateDefaultAndAutoMode(t *testing.T) { + t.Parallel() + api := newFakeAPI() + client := newFakeClient(t, api) + out, errOut, err := runNetwork(t, tableFactory(client, nil), "create", "--name", "edge", "--mode", "auto", "--default") + if err != nil { + t.Fatalf("create: %v", err) + } + if strings.Contains(errOut, "subnet create") { + t.Errorf("an auto network needs no subnet hint: %q", errOut) + } + body := api.requestsMatching("POST")[0].Body + if !strings.Contains(body, `"is_default":true`) || !strings.Contains(body, `"mode":"auto"`) { + t.Errorf("body = %s", body) + } + if !strings.Contains(out, "Created private network edge") || !strings.Contains(out, "default") { + t.Errorf("out = %q", out) + } +} + +func TestCreateMissingNameIsStructured(t *testing.T) { + t.Parallel() + client := newFakeClient(t, newFakeAPI()) + factories := map[string]cmdutil.Factory{"agent": agentFactory(client), "off a terminal": tableFactory(client, nil)} + for name, f := range factories { + _, _, err := runNetwork(t, f, "create") + if code := agentErrorCode(err); code != "MISSING_REQUIRED_FLAGS" { + t.Errorf("%s: code = %q (err %v), want MISSING_REQUIRED_FLAGS", name, code, err) + } + } +} + +func TestCreateRejectsBadMode(t *testing.T) { + t.Parallel() + api := newFakeAPI() + client := newFakeClient(t, api) + _, _, err := runNetwork(t, agentFactory(client), "create", "--name", "x", "--mode", "hybrid") + if code := agentErrorCode(err); code != "VALIDATION_ERROR" { + t.Errorf("code = %q, want VALIDATION_ERROR", code) + } + if len(api.requestsMatching("POST")) != 0 { + t.Error("no request may be sent for an invalid mode") + } +} + +func TestNameIsTrimmedAndCountedInCharacters(t *testing.T) { + t.Parallel() + if err := validateName(strings.Repeat("ä", 64)); err != nil { + t.Errorf("64 two-byte characters must pass: %v", err) + } + if err := validateName(strings.Repeat("ä", 65)); err == nil { + t.Error("65 characters must be rejected") + } + + api := newFakeAPI() + client := newFakeClient(t, api) + if _, _, err := runNetwork(t, agentFactory(client), "create", "--name", " prod "); err != nil { + t.Fatalf("create: %v", err) + } + if body := api.requestsMatching("POST")[0].Body; !strings.Contains(body, `"name":"prod"`) { + t.Errorf("name must be trimmed: %s", body) + } +} diff --git a/internal/verda-cli/cmd/network/delete.go b/internal/verda-cli/cmd/network/delete.go new file mode 100644 index 00000000..053e18ff --- /dev/null +++ b/internal/verda-cli/cmd/network/delete.go @@ -0,0 +1,146 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "fmt" + + "charm.land/lipgloss/v2" + "github.com/spf13/cobra" + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + "github.com/verda-cloud/verda-cli/pkg/tui" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +// NewCmdDelete creates the network delete command. +func NewCmdDelete(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command { + var yes bool + cmd := &cobra.Command{ + Use: "delete []", + Aliases: []string{"rm"}, + Short: "Delete a private network with its subnets", + Long: cmdutil.LongDesc(` + Delete a private network. Its subnets are removed with it. The + network must have no instances: delete them first (verda vm + action --action delete). The CLI never deletes instances for you. + + Asks for confirmation. --yes skips the confirmation and is + required in agent mode. + `), + Example: cmdutil.Examples(` + verda network delete $NETWORK_ID + verda --agent network delete $NETWORK_ID --yes + `), + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runDelete(cmd, f, ioStreams, args, yes) + }, + } + cmd.Flags().BoolVarP(&yes, flagYes, "y", false, "Skip confirmation (required in agent mode)") + return cmd +} + +func runDelete(cmd *cobra.Command, f cmdutil.Factory, ioStreams cmdutil.IOStreams, args []string, yes bool) error { + if f.AgentMode() && !yes { + return cmdutil.NewConfirmationRequiredError("delete") + } + if err := checkNetworkArg(f, args); err != nil { + return err + } + client, err := f.VerdaClient() + if err != nil { + return err + } + network, err := resolveNetworkArg(cmd, f, ioStreams, client, args) + if err != nil || network == nil { + return err + } + + if !yes { + ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) + subnets, err := cmdutil.WithSpinner(ctx, f.Status(), "Loading subnets...", func(ctx context.Context) ([]verda.Subnet, error) { + return client.PrivateNetworks.GetSubnets(ctx, network.ID) + }) + cancel() + if err != nil { + return err + } + ok, err := confirmDestructive(cmd.Context(), ioStreams, f.Prompter(), + "Delete private network "+network.Name+" ("+network.ID+")", + networkDeleteDetail(subnets), + "Delete network "+network.Name+"?") + if err != nil { + return err + } + if !ok { + _, _ = fmt.Fprintln(ioStreams.ErrOut, canceledMsg) + return nil + } + } + + cmdutil.DebugJSON(ioStreams.ErrOut, f.Debug(), "Delete private network:", map[string]string{"id": network.ID, "name": network.Name}) + ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) + defer cancel() + err = cmdutil.RunWithSpinner(ctx, f.Status(), "Deleting private network...", func(ctx context.Context) error { + return client.PrivateNetworks.Delete(ctx, network.ID) + }) + if err != nil { + return err + } + return writeDeleted(ioStreams, f, "network", network.ID, network.Name) +} + +func networkDeleteDetail(subnets []verda.Subnet) []string { + if len(subnets) == 0 { + return []string{"The network has no subnets."} + } + lines := []string{fmt.Sprintf("Also removes %d subnet(s):", len(subnets))} + for i := range subnets { + s := &subnets[i] + lines = append(lines, fmt.Sprintf(" - %s (%s, %s, %s)", s.Name, s.ID, s.Location.Code, s.CIDR)) + } + return lines +} + +func writeDeleted(ioStreams cmdutil.IOStreams, f cmdutil.Factory, resource, id, name string) error { + result := map[string]string{"resource": resource, "id": id, "name": name, "action": "delete", "status": "completed"} + if wrote, err := cmdutil.WriteStructured(ioStreams.Out, f.OutputFormat(), result); wrote { + return err + } + _, _ = fmt.Fprintf(ioStreams.Out, "Deleted %s %s (%s)\n", resource, name, id) + return nil +} + +// confirmDestructive prints a red warning with detail lines, then asks. +// (false, nil) on decline or a clean Esc/Ctrl+C; agent callers enforce --yes themselves. +func confirmDestructive(ctx context.Context, ioStreams cmdutil.IOStreams, prompter tui.Prompter, heading string, detail []string, prompt string) (bool, error) { + warn := lipgloss.NewStyle().Foreground(lipgloss.Color("1")).Bold(true) + _, _ = fmt.Fprintf(ioStreams.ErrOut, "\n %s %s\n", warn.Render("⚠"), warn.Render(heading)) + for _, line := range detail { + _, _ = fmt.Fprintf(ioStreams.ErrOut, " %s\n", line) + } + _, _ = fmt.Fprintf(ioStreams.ErrOut, " %s\n\n", warn.Render("This action cannot be undone.")) + confirmed, err := prompter.Confirm(ctx, prompt) + if err != nil { + if cmdutil.IsPromptCancel(err) { + return false, nil + } + return false, err + } + return confirmed, nil +} diff --git a/internal/verda-cli/cmd/network/delete_test.go b/internal/verda-cli/cmd/network/delete_test.go new file mode 100644 index 00000000..0268305a --- /dev/null +++ b/internal/verda-cli/cmd/network/delete_test.go @@ -0,0 +1,154 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "encoding/json" + "strings" + "testing" + + "github.com/verda-cloud/verda-cli/pkg/tui" + tuitest "github.com/verda-cloud/verda-cli/pkg/tui/testing" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +func deletes(api *fakeAPI) int { return len(api.requestsMatching("DELETE")) } + +func TestDeleteAgentModeRequiresYes(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + _, _, err := runNetwork(t, agentFactory(client), "delete", "pn_b") + if code := agentErrorCode(err); code != "CONFIRMATION_REQUIRED" { + t.Fatalf("code = %q, want CONFIRMATION_REQUIRED", code) + } + if len(api.requests) != 0 { + t.Errorf("no API call expected before --yes, got %v", api.requests) + } +} + +func TestDeleteConfirmedListsSubnets(t *testing.T) { + t.Parallel() + api := seededAPI() + api.addSubnet("pn_b", "sn_b1", "db", "FIN-03", "10.1.0.0/24", true) + client := newFakeClient(t, api) + out, errOut, err := runNetwork(t, tableFactory(client, tuitest.New().AddConfirm(true)), "delete", "pn_b") + if err != nil { + t.Fatalf("delete: %v", err) + } + for _, want := range []string{"Delete private network beta (pn_b)", "Also removes 1 subnet(s)", "db (sn_b1, FIN-03, 10.1.0.0/24)", "cannot be undone"} { + if !strings.Contains(errOut, want) { + t.Errorf("warning lacks %q:\n%s", want, errOut) + } + } + if !strings.Contains(out, "Deleted network beta (pn_b)") { + t.Errorf("out = %q", out) + } + if d := api.requestsMatching("DELETE"); len(d) != 1 || d[0].Path != "/private-networks/pn_b" { + t.Errorf("DELETE = %v", d) + } +} + +func TestDeleteCanceled(t *testing.T) { + t.Parallel() + for name, p := range map[string]*cancelPrompter{ + "declined": {Prompter: tuitest.New().AddConfirm(false)}, + "esc": {Prompter: tuitest.New(), confirmErr: context.Canceled}, + "ctrl+c": {Prompter: tuitest.New(), confirmErr: tui.ErrInterrupted}, + } { + api := seededAPI() + client := newFakeClient(t, api) + f := &cmdutil.TestFactory{ClientOverride: client, OutputFormatOverride: outputTable, PrompterOverride: p} + _, errOut, err := runNetwork(t, f, "delete", "pn_b") + if err != nil || !strings.Contains(errOut, canceledMsg) { + t.Errorf("%s: err = %v, stderr = %q", name, err, errOut) + } + if deletes(api) != 0 { + t.Errorf("%s: no DELETE expected", name) + } + } +} + +func TestDeleteAgentYesWritesResult(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + out, _, err := runNetwork(t, agentFactory(client), "rm", "pn_b", "--yes") + if err != nil { + t.Fatalf("delete: %v", err) + } + var got map[string]string + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatalf("stdout is not JSON: %v\n%s", err, out) + } + want := map[string]string{"resource": "network", "id": "pn_b", "name": "beta", "action": "delete", "status": "completed"} + for k, v := range want { + if got[k] != v { + t.Errorf("%s = %q, want %q", k, got[k], v) + } + } + if deletes(api) != 1 { + t.Errorf("want one DELETE, got %d", deletes(api)) + } +} + +func TestDeleteNotFound(t *testing.T) { + t.Parallel() + client := newFakeClient(t, seededAPI()) + _, _, err := runNetwork(t, agentFactory(client), "delete", "nope", "--yes") + if code := agentErrorCode(err); code != "NOT_FOUND" { + t.Errorf("code = %q (err %v), want NOT_FOUND", code, err) + } +} + +func TestDeleteMissingArgOffTerminal(t *testing.T) { + t.Parallel() + client := newFakeClient(t, seededAPI()) + _, _, err := runNetwork(t, tableFactory(client, nil), "delete") + if code := agentErrorCode(err); code != "MISSING_REQUIRED_FLAGS" { + t.Errorf("code = %q (err %v), want MISSING_REQUIRED_FLAGS", code, err) + } +} + +func TestDeletePickerOnTerminal(t *testing.T) { + withTerminal(t) + api := seededAPI() + client := newFakeClient(t, api) + out, _, err := runNetwork(t, tableFactory(client, tuitest.New().AddSelect(1).AddConfirm(true)), "delete") + if err != nil { + t.Fatalf("delete: %v", err) + } + if !strings.Contains(out, "Deleted network beta (pn_b)") { + t.Errorf("picker choice 1 should delete beta: %q", out) + } +} + +func TestDeletePickerCancel(t *testing.T) { + withTerminal(t) + for name, p := range map[string]*cancelPrompter{ + "cancel row": {Prompter: tuitest.New().AddSelect(2)}, + "esc": {Prompter: tuitest.New(), selectErr: context.Canceled}, + } { + api := seededAPI() + client := newFakeClient(t, api) + f := &cmdutil.TestFactory{ClientOverride: client, OutputFormatOverride: outputTable, PrompterOverride: p} + out, errOut, err := runNetwork(t, f, "delete") + if err != nil || out != "" || !strings.Contains(errOut, canceledMsg) || deletes(api) != 0 { + t.Errorf("%s: want %q on stderr only; out=%q stderr=%q err=%v deletes=%d", name, canceledMsg, out, errOut, err, deletes(api)) + } + } +} diff --git a/internal/verda-cli/cmd/network/fake_test.go b/internal/verda-cli/cmd/network/fake_test.go new file mode 100644 index 00000000..1fb2a3f3 --- /dev/null +++ b/internal/verda-cli/cmd/network/fake_test.go @@ -0,0 +1,302 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + "github.com/verda-cloud/verda-cli/pkg/tui" + tuitest "github.com/verda-cloud/verda-cli/pkg/tui/testing" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +var testCreated = time.Date(2026, 11, 16, 9, 30, 0, 0, time.UTC) + +type recordedRequest struct { + Method string + Path string + Body string +} + +// fakeAPI is an in-memory private-network API. Subnets are keyed by network ID. +type fakeAPI struct { + mu sync.Mutex + networks []verda.PrivateNetwork + subnets map[string][]verda.Subnet + locations []verda.Location + requests []recordedRequest + nextID int +} + +func newFakeAPI() *fakeAPI { + return &fakeAPI{ + subnets: map[string][]verda.Subnet{}, + locations: []verda.Location{ + {Code: "FIN-01", Name: "Finland 1"}, + {Code: "FIN-03", Name: "Finland 3", IsPrivateNetworksEnabled: true}, + {Code: "US-SOUTHWEST-1", Name: "US Southwest 1", IsPrivateNetworksEnabled: true}, + }, + } +} + +func (a *fakeAPI) addNetwork(id, name string, isDefault bool) { + a.networks = append(a.networks, verda.PrivateNetwork{ID: id, Name: name, Mode: verda.NetworkModeCustom, IsDefault: isDefault, CreatedAt: testCreated}) +} + +func (a *fakeAPI) addSubnet(networkID, id, name, location, cidr string, isDefault bool) { + a.subnets[networkID] = append(a.subnets[networkID], verda.Subnet{ + ID: id, Name: name, Location: verda.Location{Code: location}, CIDR: cidr, + IsDefault: isDefault, UsedIPCount: 1, TotalIPCount: 251, CreatedAt: testCreated, + }) +} + +func (a *fakeAPI) requestsMatching(method string) []recordedRequest { + a.mu.Lock() + defer a.mu.Unlock() + var out []recordedRequest + for _, r := range a.requests { + if r.Method == method { + out = append(out, r) + } + } + return out +} + +func (a *fakeAPI) id(prefix string) string { + a.nextID++ + return fmt.Sprintf("%s_new%d", prefix, a.nextID) +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func notFound(w http.ResponseWriter, what string) { + writeJSON(w, http.StatusNotFound, map[string]string{"code": "not_found", "message": what + " not found"}) +} + +func (a *fakeAPI) findNetwork(id string) int { + for i := range a.networks { + if a.networks[i].ID == id { + return i + } + } + return -1 +} + +func (a *fakeAPI) findSubnet(networkID, id string) int { + for i := range a.subnets[networkID] { + if a.subnets[networkID][i].ID == id { + return i + } + } + return -1 +} + +func (a *fakeAPI) handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("POST /oauth2/token", func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]string{"access_token": "test-token", "token_type": "Bearer"}) + }) + mux.HandleFunc("GET /locations", func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, http.StatusOK, a.locations) }) + mux.HandleFunc("GET /private-networks", func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, http.StatusOK, a.networks) }) + mux.HandleFunc("POST /private-networks", a.createNetwork) + mux.HandleFunc("GET /private-networks/{id}", func(w http.ResponseWriter, r *http.Request) { + i := a.findNetwork(r.PathValue("id")) + if i < 0 { + notFound(w, "private network") + return + } + writeJSON(w, http.StatusOK, a.networks[i]) + }) + mux.HandleFunc("DELETE /private-networks/{id}", func(w http.ResponseWriter, r *http.Request) { + i := a.findNetwork(r.PathValue("id")) + if i < 0 { + notFound(w, "private network") + return + } + a.networks = append(a.networks[:i], a.networks[i+1:]...) + w.WriteHeader(http.StatusNoContent) + }) + mux.HandleFunc("GET /private-networks/{id}/subnets", func(w http.ResponseWriter, r *http.Request) { + if a.findNetwork(r.PathValue("id")) < 0 { + notFound(w, "private network") + return + } + subnets := a.subnets[r.PathValue("id")] + if subnets == nil { + subnets = []verda.Subnet{} + } + writeJSON(w, http.StatusOK, subnets) + }) + mux.HandleFunc("POST /private-networks/{id}/subnets", a.createSubnet) + mux.HandleFunc("GET /private-networks/{id}/subnets/{sid}", func(w http.ResponseWriter, r *http.Request) { + nid := r.PathValue("id") + i := a.findSubnet(nid, r.PathValue("sid")) + if i < 0 { + notFound(w, "subnet") + return + } + writeJSON(w, http.StatusOK, a.subnets[nid][i]) + }) + mux.HandleFunc("DELETE /private-networks/{id}/subnets/{sid}", func(w http.ResponseWriter, r *http.Request) { + nid := r.PathValue("id") + i := a.findSubnet(nid, r.PathValue("sid")) + if i < 0 { + notFound(w, "subnet") + return + } + a.subnets[nid] = append(a.subnets[nid][:i], a.subnets[nid][i+1:]...) + w.WriteHeader(http.StatusNoContent) + }) + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) + a.mu.Lock() + defer a.mu.Unlock() + if r.URL.Path != "/oauth2/token" { + a.requests = append(a.requests, recordedRequest{Method: r.Method, Path: r.URL.Path, Body: string(body)}) + } + mux.ServeHTTP(w, r) + }) +} + +func (a *fakeAPI) createNetwork(w http.ResponseWriter, r *http.Request) { + var req verda.CreatePrivateNetworkRequest + _ = json.NewDecoder(r.Body).Decode(&req) + n := verda.PrivateNetwork{ID: a.id("pn"), Name: req.Name, Mode: req.Mode, IsDefault: req.IsDefault, CreatedAt: testCreated} + a.networks = append(a.networks, n) + writeJSON(w, http.StatusCreated, n) +} + +func (a *fakeAPI) createSubnet(w http.ResponseWriter, r *http.Request) { + nid := r.PathValue("id") + if a.findNetwork(nid) < 0 { + notFound(w, "private network") + return + } + var req verda.CreateSubnetRequest + _ = json.NewDecoder(r.Body).Decode(&req) + isDefault := req.IsDefault != nil && *req.IsDefault + s := verda.Subnet{ + ID: a.id("sn"), Name: req.Name, Location: verda.Location{Code: req.LocationCode}, CIDR: req.CIDR, + IsDefault: isDefault, TotalIPCount: 251, CreatedAt: testCreated, + } + a.subnets[nid] = append(a.subnets[nid], s) + writeJSON(w, http.StatusCreated, s) +} + +// newFakeClient serves api and returns an SDK client pointed at it. +func newFakeClient(t *testing.T, api *fakeAPI) *verda.Client { + t.Helper() + srv := httptest.NewServer(api.handler()) + t.Cleanup(srv.Close) + client, err := verda.NewClient( + verda.WithBaseURL(srv.URL), + verda.WithClientID("test-id"), + verda.WithClientSecret("test-secret"), + ) + if err != nil { + t.Fatalf("verda.NewClient: %v", err) + } + return client +} + +// Factory shapes for the modes the commands are tested in. +func tableFactory(client *verda.Client, p *tuitest.Prompter) *cmdutil.TestFactory { + f := &cmdutil.TestFactory{ClientOverride: client, OutputFormatOverride: outputTable} + if p != nil { + f.PrompterOverride = p + } + return f +} + +func agentFactory(client *verda.Client) *cmdutil.TestFactory { + return &cmdutil.TestFactory{ClientOverride: client, AgentModeOverride: true, OutputFormatOverride: "json"} +} + +// runNetwork runs `verda network ` and returns stdout and stderr. +func runNetwork(t *testing.T, f cmdutil.Factory, args ...string) (stdout, stderr string, err error) { + t.Helper() + var out, errOut bytes.Buffer + cmd := NewCmdNetwork(f, cmdutil.IOStreams{Out: &out, ErrOut: &errOut}) + cmd.SetArgs(args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + err = cmd.ExecuteContext(context.Background()) + return out.String(), errOut.String(), err +} + +// withTerminal makes interactiveTTY see a terminal; not parallel-safe. +func withTerminal(t *testing.T) { + t.Helper() + orig := isInteractiveTerminal + isInteractiveTerminal = func() bool { return true } + t.Cleanup(func() { isInteractiveTerminal = orig }) +} + +// cancelPrompter answers Select or Confirm with an error (Esc, Ctrl+C) when set. +type cancelPrompter struct { + *tuitest.Prompter + selectErr error + confirmErr error +} + +func (p *cancelPrompter) Select(ctx context.Context, msg string, labels []string, opts ...tui.SelectOption) (int, error) { + if p.selectErr != nil { + return -1, p.selectErr + } + return p.Prompter.Select(ctx, msg, labels, opts...) +} + +func (p *cancelPrompter) Confirm(ctx context.Context, msg string, opts ...tui.ConfirmOption) (bool, error) { + if p.confirmErr != nil { + return false, p.confirmErr + } + return p.Prompter.Confirm(ctx, msg, opts...) +} + +// agentErrorCode is the code main reports, so an API 404 counts as NOT_FOUND. +func agentErrorCode(err error) string { + if ae := cmdutil.ClassifyError(err); ae != nil { + return ae.Code + } + return "" +} + +func seededAPI() *fakeAPI { + api := newFakeAPI() + api.addNetwork("pn_a", "alpha", true) + api.addNetwork("pn_b", "beta", false) + api.addSubnet("pn_a", "sn_a1", "fin-03-1", "FIN-03", "10.0.0.0/24", true) + api.addSubnet("pn_a", "sn_a2", "us-1", "US-SOUTHWEST-1", "10.0.1.0/24", true) + api.subnets["pn_a"][0].DefaultRouteInstance = &verda.AttachedInstance{ID: "i-gw", Hostname: "gw-1"} + return api +} diff --git a/internal/verda-cli/cmd/network/list.go b/internal/verda-cli/cmd/network/list.go new file mode 100644 index 00000000..6469bf19 --- /dev/null +++ b/internal/verda-cli/cmd/network/list.go @@ -0,0 +1,81 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "fmt" + "text/tabwriter" + + "github.com/spf13/cobra" + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +// NewCmdList creates the network list command. +func NewCmdList(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command { + return &cobra.Command{ + Use: "list", + Aliases: []string{"ls"}, + Short: "List private networks", + Long: cmdutil.LongDesc(` + List the private networks in your project. The default network + is marked with * in the DEFAULT column. + `), + Example: cmdutil.Examples(` + verda network list + verda network ls -o json + `), + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return runList(cmd, f, ioStreams) + }, + } +} + +func runList(cmd *cobra.Command, f cmdutil.Factory, ioStreams cmdutil.IOStreams) error { + client, err := f.VerdaClient() + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) + defer cancel() + + networks, err := cmdutil.WithSpinner(ctx, f.Status(), "Loading private networks...", func(ctx context.Context) ([]verda.PrivateNetwork, error) { + return client.PrivateNetworks.Get(ctx) + }) + if err != nil { + return err + } + cmdutil.DebugJSON(ioStreams.ErrOut, f.Debug(), fmt.Sprintf("API response: %d private network(s):", len(networks)), networks) + + views := newNetworkViews(networks) + if wrote, err := cmdutil.WriteStructured(ioStreams.Out, f.OutputFormat(), views); wrote { + return err + } + if len(views) == 0 { + printNoNetworks(ioStreams) + return nil + } + + tw := tabwriter.NewWriter(ioStreams.Out, 0, 0, 2, ' ', 0) + _, _ = fmt.Fprintln(tw, "NAME\tID\tMODE\tDEFAULT\tCREATED") + for i := range views { + v := &views[i] + _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", v.Name, v.ID, v.Mode, defaultColumn(v.IsDefault), cmdutil.TimeColumn(v.CreatedAt, timeLayout)) + } + return tw.Flush() +} diff --git a/internal/verda-cli/cmd/network/list_test.go b/internal/verda-cli/cmd/network/list_test.go new file mode 100644 index 00000000..3abe114c --- /dev/null +++ b/internal/verda-cli/cmd/network/list_test.go @@ -0,0 +1,68 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestListTable(t *testing.T) { + t.Parallel() + client := newFakeClient(t, seededAPI()) + out, _, err := runNetwork(t, tableFactory(client, nil), "list") + if err != nil { + t.Fatalf("list: %v", err) + } + for _, want := range []string{"NAME", "MODE", "DEFAULT", "alpha", "pn_a", "beta", "custom", "2026-11-16 09:30"} { + if !strings.Contains(out, want) { + t.Errorf("table lacks %q:\n%s", want, out) + } + } +} + +func TestListAgentJSON(t *testing.T) { + t.Parallel() + client := newFakeClient(t, seededAPI()) + out, _, err := runNetwork(t, agentFactory(client), "ls") + if err != nil { + t.Fatalf("list: %v", err) + } + var rows []map[string]any + if err := json.Unmarshal([]byte(out), &rows); err != nil { + t.Fatalf("stdout is not JSON: %v\n%s", err, out) + } + if len(rows) != 2 || rows[0]["id"] != "pn_a" || rows[0]["is_default"] != true { + t.Errorf("rows = %v", rows) + } +} + +func TestListEmpty(t *testing.T) { + t.Parallel() + client := newFakeClient(t, newFakeAPI()) + out, errOut, err := runNetwork(t, tableFactory(client, nil), "list") + if err != nil { + t.Fatalf("list: %v", err) + } + if !strings.Contains(out, "No private networks found.") || !strings.Contains(errOut, "verda network create") { + t.Errorf("want empty message and hint; out=%q err=%q", out, errOut) + } + + out, _, err = runNetwork(t, agentFactory(client), "list") + if err != nil || strings.TrimSpace(out) != "[]" { + t.Errorf("agent empty list = %q (err %v), want []", out, err) + } +} diff --git a/internal/verda-cli/cmd/network/network.go b/internal/verda-cli/cmd/network/network.go new file mode 100644 index 00000000..9e3ca733 --- /dev/null +++ b/internal/verda-cli/cmd/network/network.go @@ -0,0 +1,174 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package network implements `verda network`: private networks. +package network + +import ( + "context" + "fmt" + "os" + "strings" + + "github.com/charmbracelet/x/term" + "github.com/spf13/cobra" + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + "github.com/verda-cloud/verda-cli/pkg/tui" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +const ( + outputTable = "table" + flagName = "name" + flagDefault = "default" + flagYes = "yes" + argNetwork = "" + timeLayout = "2006-01-02 15:04" + cancelLabel = "Cancel" + canceledMsg = "Canceled." + defaultMark = "*" +) + +// NewCmdNetwork creates the `verda network` parent command. +func NewCmdNetwork(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command { + cmd := &cobra.Command{ + Use: "network", + Aliases: []string{"networks", "net", "private-network", "vpc"}, + Short: "Manage private networks", + Annotations: map[string]string{cmdutil.TagAnnotation: "beta"}, + Long: cmdutil.LongDesc(` + Manage private networks (VPC). A network is global; its subnets + live in one location each. Instances on the same network reach + each other over private IPs. + + The default network is the one a VM joins when it names no + network. Arguments and --network take an ID. + After network create, use subnet create to add a subnet in a + location. Use delete to delete a network and its subnets. Use + subnet delete to delete one subnet. + `), + Example: cmdutil.Examples(` + verda network list + verda network create --name prod + verda network subnet create --network $NETWORK_ID -l FIN-03 + verda network subnet list --network $NETWORK_ID + verda network delete $NETWORK_ID + `), + Run: cmdutil.DefaultSubCommandRun(ioStreams.Out), + } + + cmd.AddCommand( + NewCmdList(f, ioStreams), + NewCmdCreate(f, ioStreams), + NewCmdDelete(f, ioStreams), + NewCmdSubnet(f, ioStreams), + ) + return cmd +} + +// isInteractiveTerminal: prompts need stdin, stdout and stderr on a TTY; a var so tests can fake one. +var isInteractiveTerminal = func() bool { + return term.IsTerminal(os.Stdin.Fd()) && cmdutil.IsStdoutTerminal() && cmdutil.IsStderrTerminal() +} + +// interactiveTTY: prompts only on a terminal, outside agent mode, with table output. +func interactiveTTY(f cmdutil.Factory) bool { + return isInteractiveTerminal() && !f.AgentMode() && f.OutputFormat() == outputTable +} + +// checkNetworkArg: off a TTY, is required, and a blank ID is never +// sent. Call it before f.VerdaClient() so bad input fails the same with or without credentials. +func checkNetworkArg(f cmdutil.Factory, args []string) error { + blank := len(args) > 0 && strings.TrimSpace(args[0]) == "" + if blank || (len(args) == 0 && !interactiveTTY(f)) { + return cmdutil.NewMissingFlagsError([]string{argNetwork}) + } + return nil +} + +// resolveNetworkArg: args[0] by ID; else a picker. Call checkNetworkArg first. +// A nil network with a nil error means the user canceled the picker. +func resolveNetworkArg(cmd *cobra.Command, f cmdutil.Factory, ioStreams cmdutil.IOStreams, client *verda.Client, args []string) (*verda.PrivateNetwork, error) { + if len(args) > 0 { + ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) + defer cancel() + return cmdutil.WithSpinner(ctx, f.Status(), "Loading private networks...", func(ctx context.Context) (*verda.PrivateNetwork, error) { + return client.PrivateNetworks.GetByID(ctx, args[0]) + }) + } + return selectNetwork(cmd.Context(), f, ioStreams, client) +} + +// selectNetwork prompts for a network; cancel or an empty list → nil, nil. +func selectNetwork(ctx context.Context, f cmdutil.Factory, ioStreams cmdutil.IOStreams, client *verda.Client) (*verda.PrivateNetwork, error) { + listCtx, cancel := context.WithTimeout(ctx, f.Options().Timeout) + defer cancel() + networks, err := cmdutil.WithSpinner(listCtx, f.Status(), "Loading private networks...", func(ctx context.Context) ([]verda.PrivateNetwork, error) { + return client.PrivateNetworks.Get(ctx) + }) + if err != nil { + return nil, err + } + if len(networks) == 0 { + printNoNetworks(ioStreams) + return nil, nil + } + + labels := make([]string, 0, len(networks)+1) + for i := range networks { + labels = append(labels, networkLabel(&networks[i])) + } + labels = append(labels, cancelLabel) + idx, err := f.Prompter().Select(ctx, "Select private network", labels, tui.WithShowHints(true)) + if err != nil && !cmdutil.IsPromptCancel(err) { + return nil, err + } + if err != nil || idx < 0 || idx >= len(networks) { + _, _ = fmt.Fprintln(ioStreams.ErrOut, canceledMsg) + return nil, nil + } + return &networks[idx], nil +} + +// networkByID returns nil when no network has this ID. +func networkByID(networks []verda.PrivateNetwork, id string) *verda.PrivateNetwork { + for i := range networks { + if networks[i].ID == id { + return &networks[i] + } + } + return nil +} + +func networkLabel(n *verda.PrivateNetwork) string { + label := fmt.Sprintf("%s (%s, %s)", n.Name, n.ID, n.Mode) + if n.IsDefault { + label += " default" + } + return label +} + +func printNoNetworks(ioStreams cmdutil.IOStreams) { + _, _ = fmt.Fprintln(ioStreams.Out, "No private networks found.") + _, _ = fmt.Fprintln(ioStreams.ErrOut, "Create one with: verda network create") +} + +func defaultColumn(isDefault bool) string { + if isDefault { + return defaultMark + } + return "" +} diff --git a/internal/verda-cli/cmd/network/subnet.go b/internal/verda-cli/cmd/network/subnet.go new file mode 100644 index 00000000..2d2ed46a --- /dev/null +++ b/internal/verda-cli/cmd/network/subnet.go @@ -0,0 +1,161 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "fmt" + "strings" + + "github.com/spf13/cobra" + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + "github.com/verda-cloud/verda-cli/pkg/tui" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +const ( + flagNetwork = "network" + flagLocation = "location" + argSubnet = "" +) + +// NewCmdSubnet creates the `network subnet` parent command. +func NewCmdSubnet(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command { + cmd := &cobra.Command{ + Use: "subnet", + Aliases: []string{"subnets"}, + Short: "Manage the subnets of private networks", + Long: cmdutil.LongDesc(` + Manage subnets. A subnet belongs to one network and one location. + Commands take IDs, not names. + `), + Example: cmdutil.Examples(` + verda network subnet list + verda network subnet create --network $NETWORK_ID -l FIN-03 + verda network subnet delete $SUBNET_ID --network $NETWORK_ID + `), + Run: cmdutil.DefaultSubCommandRun(ioStreams.Out), + } + cmd.AddCommand( + NewCmdSubnetList(f, ioStreams), + NewCmdSubnetCreate(f, ioStreams), + NewCmdSubnetDelete(f, ioStreams), + ) + return cmd +} + +// checkSubnetArgs: a subnet ID needs --network; off a TTY both are required. A blank ID counts as missing. +// Call it before f.VerdaClient() so bad input fails the same with or without credentials. +func checkSubnetArgs(f cmdutil.Factory, networkID string, args []string) error { + if len(args) == 0 && interactiveTTY(f) { + return nil + } + var missing []string + if len(args) == 0 || strings.TrimSpace(args[0]) == "" { + missing = append(missing, argSubnet) + } + if strings.TrimSpace(networkID) == "" { + missing = append(missing, "--"+flagNetwork) + } + if len(missing) > 0 { + return cmdutil.NewMissingFlagsError(missing) + } + return nil +} + +// resolveSubnetArg returns the network ID and the subnet: args[0] with --network, +// else a picker (of one network with --network). Call checkSubnetArgs first. +// A nil subnet with a nil error means the user canceled the picker. +func resolveSubnetArg(cmd *cobra.Command, f cmdutil.Factory, ioStreams cmdutil.IOStreams, client *verda.Client, networkID string, args []string) (string, *verda.Subnet, error) { + if len(args) == 0 { + return selectSubnet(cmd.Context(), f, ioStreams, client, networkID) + } + ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) + defer cancel() + subnet, err := cmdutil.WithSpinner(ctx, f.Status(), "Loading subnet...", func(ctx context.Context) (*verda.Subnet, error) { + return client.PrivateNetworks.GetSubnetByID(ctx, networkID, args[0]) + }) + return networkID, subnet, err +} + +// subnetRow is one subnet with the network it was read from. +type subnetRow struct { + network *verda.PrivateNetwork + subnet verda.Subnet +} + +// loadSubnetRows reads the subnets of one network (networkID) or of all networks. +func loadSubnetRows(ctx context.Context, client *verda.Client, networkID string) ([]subnetRow, error) { + networks, err := client.PrivateNetworks.Get(ctx) + if err != nil { + return nil, err + } + if networkID != "" { + n := networkByID(networks, networkID) + if n == nil { + return nil, cmdutil.NewNotFoundError("network", networkID) + } + networks = []verda.PrivateNetwork{*n} + } + var rows []subnetRow + for i := range networks { + subnets, err := client.PrivateNetworks.GetSubnets(ctx, networks[i].ID) + if err != nil { + return nil, err + } + for j := range subnets { + rows = append(rows, subnetRow{network: &networks[i], subnet: subnets[j]}) + } + } + return rows, nil +} + +// selectSubnet prompts for a subnet; cancel or an empty list → "", nil, nil. +func selectSubnet(ctx context.Context, f cmdutil.Factory, ioStreams cmdutil.IOStreams, client *verda.Client, networkID string) (string, *verda.Subnet, error) { + listCtx, cancel := context.WithTimeout(ctx, f.Options().Timeout) + defer cancel() + rows, err := cmdutil.WithSpinner(listCtx, f.Status(), "Loading subnets...", func(ctx context.Context) ([]subnetRow, error) { + return loadSubnetRows(ctx, client, networkID) + }) + if err != nil { + return "", nil, err + } + if len(rows) == 0 { + printNoSubnets(ioStreams) + return "", nil, nil + } + labels := make([]string, 0, len(rows)+1) + for i := range rows { + s := &rows[i].subnet + labels = append(labels, fmt.Sprintf("%s / %s (%s, %s, %s)", rows[i].network.Name, s.Name, s.ID, s.Location.Code, s.CIDR)) + } + labels = append(labels, cancelLabel) + idx, err := f.Prompter().Select(ctx, "Select subnet", labels, tui.WithShowHints(true)) + if err != nil && !cmdutil.IsPromptCancel(err) { + return "", nil, err + } + if err != nil || idx < 0 || idx >= len(rows) { + _, _ = fmt.Fprintln(ioStreams.ErrOut, canceledMsg) + return "", nil, nil + } + return rows[idx].network.ID, &rows[idx].subnet, nil +} + +func printNoSubnets(ioStreams cmdutil.IOStreams) { + _, _ = fmt.Fprintln(ioStreams.Out, "No subnets found.") + _, _ = fmt.Fprintln(ioStreams.ErrOut, "Create one with: verda network subnet create") +} diff --git a/internal/verda-cli/cmd/network/subnet_create.go b/internal/verda-cli/cmd/network/subnet_create.go new file mode 100644 index 00000000..c0d653b0 --- /dev/null +++ b/internal/verda-cli/cmd/network/subnet_create.go @@ -0,0 +1,315 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "fmt" + "net/netip" + "slices" + "strconv" + "strings" + + "github.com/spf13/cobra" + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + "github.com/verda-cloud/verda-cli/pkg/tui/wizard" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +const flagCIDR = "cidr" + +type subnetCreateOptions struct { + Network string + Location string + Name string + CIDR string + Default bool + defaultSet bool +} + +// subnetCreateData is read once before the wizard so its steps need no API calls. +type subnetCreateData struct { + networks []verda.PrivateNetwork + locations []verda.Location // only those with private networks + subnets map[string][]verda.Subnet +} + +func NewCmdSubnetCreate(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command { + opts := &subnetCreateOptions{} + cmd := &cobra.Command{ + Use: "create", + Short: "Create a subnet in a private network", + Long: cmdutil.LongDesc(` + Create a subnet in one location of a private network. The + location must support private networks. On a terminal without + --network or --location, the CLI asks for each value that you + do not give. In scripts and agent mode, --network and + --location are necessary. + + Without --cidr, the CLI uses the first free /24 in 10.0.0.0/16 + that does not overlap a subnet of the network. It prints the + CIDR, except in agent mode. + The API decides which --cidr values it accepts. The name + default is - in lower case, for example fin-03-1. + + Without --default, the new subnet becomes the default when the + network has no default subnet in its location. --default makes + the new subnet the default. --default=false makes it not the + default, also when the location has no default. + `), + Example: cmdutil.Examples(` + verda network subnet create + verda network subnet create --network $NETWORK_ID -l FIN-03 + verda network subnet create --network $NETWORK_ID -l FIN-03 --name web --cidr 10.0.8.0/24 --default + `), + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + opts.defaultSet = cmd.Flags().Changed(flagDefault) + return runSubnetCreate(cmd, f, ioStreams, opts) + }, + } + flags := cmd.Flags() + flags.StringVar(&opts.Network, flagNetwork, "", "Network ID") + flags.StringVarP(&opts.Location, flagLocation, "l", "", "Location code, for example FIN-03") + flags.StringVar(&opts.Name, flagName, "", "Subnet name (default: - in lower case)") + flags.StringVar(&opts.CIDR, flagCIDR, "", "IPv4 range (default: the first free /24 in 10.0.0.0/16)") + flags.BoolVar(&opts.Default, flagDefault, false, "Make this the default subnet of its location") + return cmd +} + +func runSubnetCreate(cmd *cobra.Command, f cmdutil.Factory, ioStreams cmdutil.IOStreams, opts *subnetCreateOptions) error { + interactive := interactiveTTY(f) + if err := checkSubnetCreateFlags(opts, interactive); err != nil { + return err + } + client, err := f.VerdaClient() + if err != nil { + return err + } + + ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) + data, err := cmdutil.WithSpinner(ctx, f.Status(), "Loading networks and locations...", func(ctx context.Context) (*subnetCreateData, error) { + return loadSubnetCreateData(ctx, client, ioStreams, f.Debug(), opts.Network) + }) + cancel() + if err != nil { + return err + } + if err := data.normalize(opts); err != nil { + return err + } + + if interactive && (opts.Network == "" || opts.Location == "") { + engine := wizard.NewEngine(f.Prompter(), f.Status(), wizard.WithOutput(ioStreams.ErrOut)) + if err := engine.Run(cmd.Context(), buildSubnetCreateFlow(opts, data)); err != nil { + return err + } + } + autoCIDR := opts.CIDR == "" + if err := data.fillDefaults(opts); err != nil { + return err + } + if autoCIDR && !f.AgentMode() { + _, _ = fmt.Fprintf(ioStreams.ErrOut, "Using CIDR %s (the first free /%d in %s).\n", opts.CIDR, defaultSubnetBits, defaultSubnetPool) + } + if err := data.validate(opts); err != nil { + return err + } + + req := verda.CreateSubnetRequest{LocationCode: opts.Location, Name: opts.Name, CIDR: opts.CIDR} + if opts.defaultSet { + req.IsDefault = new(opts.Default) + } + cmdutil.DebugJSON(ioStreams.ErrOut, f.Debug(), "Request payload:", req) + ctx, cancel = context.WithTimeout(cmd.Context(), f.Options().Timeout) + defer cancel() + subnet, err := cmdutil.WithSpinner(ctx, f.Status(), "Creating subnet...", func(ctx context.Context) (*verda.Subnet, error) { + return client.PrivateNetworks.CreateSubnet(ctx, opts.Network, req) + }) + if err != nil { + return err + } + cmdutil.DebugJSON(ioStreams.ErrOut, f.Debug(), "API response:", subnet) + + view := newSubnetView(opts.Network, subnet) + if wrote, err := cmdutil.WriteStructured(ioStreams.Out, f.OutputFormat(), view); wrote { + return err + } + isDefault := "no" + if view.IsDefault { + isDefault = "yes" + } + _, _ = fmt.Fprintf(ioStreams.Out, "Created subnet %s (%s) in %s, %s, default: %s\n", view.Name, view.ID, view.Location, view.CIDR, isDefault) + return nil +} + +// checkSubnetCreateFlags trims and checks the flag values before any API call or prompt. +func checkSubnetCreateFlags(opts *subnetCreateOptions, interactive bool) error { + opts.Name = strings.TrimSpace(opts.Name) + opts.CIDR = strings.TrimSpace(opts.CIDR) + if opts.Name != "" { + if err := validateName(opts.Name); err != nil { + return cmdutil.NewValidationError(flagName, err.Error()) + } + } + if opts.CIDR != "" { + if err := checkCIDRFormat(opts.CIDR); err != nil { + return cmdutil.NewValidationError(flagCIDR, err.Error()) + } + } + if missing := missingSubnetCreateFlags(opts); !interactive && len(missing) > 0 { + return cmdutil.NewMissingFlagsError(missing) + } + return nil +} + +func missingSubnetCreateFlags(opts *subnetCreateOptions) []string { + var missing []string + if opts.Network == "" { + missing = append(missing, "--"+flagNetwork) + } + if opts.Location == "" { + missing = append(missing, "--"+flagLocation) + } + return missing +} + +// loadSubnetCreateData: with networkArg set, it reads only that network's subnets; +// normalize reports an unknown network. +func loadSubnetCreateData(ctx context.Context, client *verda.Client, ioStreams cmdutil.IOStreams, debug bool, networkArg string) (*subnetCreateData, error) { + networks, err := client.PrivateNetworks.Get(ctx) + if err != nil { + return nil, err + } + cmdutil.DebugJSON(ioStreams.ErrOut, debug, fmt.Sprintf("API response: %d private network(s):", len(networks)), networks) + locations, err := client.Locations.Get(ctx) + if err != nil { + return nil, err + } + cmdutil.DebugJSON(ioStreams.ErrOut, debug, fmt.Sprintf("API response: %d location(s):", len(locations)), locations) + data := &subnetCreateData{networks: networks, subnets: make(map[string][]verda.Subnet, len(networks))} + for i := range locations { + if locations[i].IsPrivateNetworksEnabled { + data.locations = append(data.locations, locations[i]) + } + } + toRead := networks + if networkArg != "" { + toRead = nil + if n := networkByID(networks, networkArg); n != nil { + toRead = []verda.PrivateNetwork{*n} + } + } + for i := range toRead { + subnets, err := client.PrivateNetworks.GetSubnets(ctx, toRead[i].ID) + if err != nil { + return nil, err + } + cmdutil.DebugJSON(ioStreams.ErrOut, debug, fmt.Sprintf("API response: %d subnet(s) of %s:", len(subnets), toRead[i].ID), subnets) + data.subnets[toRead[i].ID] = subnets + } + return data, nil +} + +func (d *subnetCreateData) normalize(opts *subnetCreateOptions) error { + if len(d.networks) == 0 { + return cmdutil.NewValidationError(flagNetwork, "no private network found. Create one with \"verda network create\", then run this command again") + } + if opts.Network != "" { + if networkByID(d.networks, opts.Network) == nil { + return cmdutil.NewNotFoundError("network", opts.Network) + } + } + if opts.Location != "" { + code, err := d.enabledLocation(opts.Location) + if err != nil { + return err + } + opts.Location = code + } + return nil +} + +func (d *subnetCreateData) enabledLocation(loc string) (string, error) { + codes := make([]string, len(d.locations)) + for i := range d.locations { + if strings.EqualFold(d.locations[i].Code, loc) { + return d.locations[i].Code, nil + } + codes[i] = d.locations[i].Code + } + return "", cmdutil.NewValidationError(flagLocation, + fmt.Sprintf("private networks are not available in %s. Use one of: %s", loc, strings.Join(codes, ", "))) +} + +func (d *subnetCreateData) fillDefaults(opts *subnetCreateOptions) error { + if opts.Name == "" { + opts.Name = d.defaultName(opts.Network, opts.Location) + } + if opts.CIDR == "" { + p, err := d.suggestCIDR(opts.Network) + if err != nil { + return cmdutil.NewValidationError(flagCIDR, err.Error()+". Pass --cidr") + } + opts.CIDR = p.String() + } + return nil +} + +// defaultName is - in lower case, with the first n not used in the network. +func (d *subnetCreateData) defaultName(networkID, location string) string { + prefix := strings.ToLower(location) + "-" + for n := 1; ; n++ { + name := prefix + strconv.Itoa(n) + if !d.hasSubnetNamed(networkID, name) { + return name + } + } +} + +func (d *subnetCreateData) suggestCIDR(networkID string) (netip.Prefix, error) { + return freeSubnetCIDR(subnetPrefixes(d.subnets[networkID])) +} + +func (d *subnetCreateData) checkName(networkID, name string) error { + if err := validateName(name); err != nil { + return err + } + if d.hasSubnetNamed(networkID, name) { + return errNameTaken + } + return nil +} + +func (d *subnetCreateData) hasSubnetNamed(networkID, name string) bool { + return slices.ContainsFunc(d.subnets[networkID], func(s verda.Subnet) bool { return s.Name == name }) +} + +func (d *subnetCreateData) validate(opts *subnetCreateOptions) error { + if err := d.checkName(opts.Network, opts.Name); err != nil { + return cmdutil.NewValidationError(flagName, err.Error()) + } + return nil +} + +// noDefaultIn: without is_default, the API makes a new subnet the default +// when the network has no default subnet in its location. +func (d *subnetCreateData) noDefaultIn(networkID, location string) bool { + return !slices.ContainsFunc(d.subnets[networkID], func(s verda.Subnet) bool { + return s.IsDefault && strings.EqualFold(s.Location.Code, location) + }) +} diff --git a/internal/verda-cli/cmd/network/subnet_create_test.go b/internal/verda-cli/cmd/network/subnet_create_test.go new file mode 100644 index 00000000..6d8a3ade --- /dev/null +++ b/internal/verda-cli/cmd/network/subnet_create_test.go @@ -0,0 +1,240 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "errors" + "fmt" + "io" + "strings" + "testing" + + "github.com/verda-cloud/verda-cli/pkg/tui/wizard" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +func postBodies(api *fakeAPI) []string { + posts := api.requestsMatching("POST") + out := make([]string, 0, len(posts)) + for _, r := range posts { + out = append(out, r.Body) + } + return out +} + +func TestSubnetCreateSuggestsCIDRAndName(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + out, errOut, err := runNetwork(t, tableFactory(client, nil), "subnet", "create", "--network", "pn_a", "-l", "fin-03") + if err != nil { + t.Fatalf("create: %v", err) + } + if !strings.Contains(errOut, "Using CIDR 10.0.2.0/24") { + t.Errorf("the picked CIDR must be printed: %q", errOut) + } + bodies := postBodies(api) + want := `{"location_code":"FIN-03","name":"fin-03-2","cidr":"10.0.2.0/24"}` + if len(bodies) != 1 || bodies[0] != want { + t.Errorf("POST = %q, want %s", bodies, want) + } + if !strings.Contains(out, "default: no") { + t.Errorf("out = %q", out) + } +} + +func TestSubnetCreateDefaultIsSentOnlyWhenSet(t *testing.T) { + t.Parallel() + tests := []struct { + name string + extra []string + want string // "" means is_default is absent + }{ + {name: "not set", want: ""}, + {name: "--default", extra: []string{"--default"}, want: `"is_default":true`}, + {name: "--default=false", extra: []string{"--default=false"}, want: `"is_default":false`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + args := append([]string{"subnet", "create", "--network", "pn_a", "-l", "FIN-03", "--name", "web"}, tt.extra...) + if _, _, err := runNetwork(t, agentFactory(client), args...); err != nil { + t.Fatalf("create: %v", err) + } + bodies := postBodies(api) + if len(bodies) != 1 { + t.Fatalf("POST bodies = %q, want one", bodies) + } + if tt.want == "" && strings.Contains(bodies[0], "is_default") { + t.Errorf("is_default must be absent: %s", bodies[0]) + } + if tt.want != "" && !strings.Contains(bodies[0], tt.want) { + t.Errorf("body = %s, want %s", bodies[0], tt.want) + } + }) + } +} + +func TestSubnetCreateSendsTrimmedCIDR(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + if _, _, err := runNetwork(t, agentFactory(client), "subnet", "create", "--network", "pn_a", "-l", "FIN-03", "--cidr", " 10.0.8.0/24 "); err != nil { + t.Fatalf("create: %v", err) + } + if bodies := postBodies(api); len(bodies) != 1 || !strings.Contains(bodies[0], `"cidr":"10.0.8.0/24"`) { + t.Fatalf("POST bodies = %q, want one with the trimmed CIDR", bodies) + } +} + +func TestSubnetCreateRejectsDuplicateName(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + _, _, err := runNetwork(t, agentFactory(client), "subnet", "create", "--network", "pn_a", "-l", "FIN-03", "--name", " fin-03-1 ") + if code := agentErrorCode(err); code != "VALIDATION_ERROR" || !strings.Contains(err.Error(), errNameTaken.Error()) { + t.Errorf("code = %q (err %v), want VALIDATION_ERROR", code, err) + } + if len(postBodies(api)) != 0 { + t.Error("no POST may be sent") + } +} + +func TestSubnetCreateLocationWithoutPrivateNetworks(t *testing.T) { + t.Parallel() + client := newFakeClient(t, seededAPI()) + _, _, err := runNetwork(t, agentFactory(client), "subnet", "create", "--network", "pn_a", "-l", "FIN-01") + if code := agentErrorCode(err); code != "VALIDATION_ERROR" { + t.Fatalf("code = %q, want VALIDATION_ERROR", code) + } + for _, want := range []string{"FIN-01", "FIN-03", "US-SOUTHWEST-1"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("error lacks %q: %v", want, err) + } + } +} + +func TestSubnetCreateMissingFlags(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + _, _, err := runNetwork(t, agentFactory(client), "subnet", "create") + var ae *cmdutil.AgentError + if !errors.As(err, &ae) || ae.Code != "MISSING_REQUIRED_FLAGS" { + t.Fatalf("err = %v, want MISSING_REQUIRED_FLAGS", err) + } + if got := fmt.Sprint(ae.Details["missing"]); got != "[--network --location]" { + t.Errorf("missing = %s, want [--network --location]", got) + } + if len(api.requestsMatching("GET")) != 0 { + t.Error("no API call expected before the flag check") + } +} + +func TestSubnetCreateUnknownNetwork(t *testing.T) { + t.Parallel() + client := newFakeClient(t, seededAPI()) + _, _, err := runNetwork(t, agentFactory(client), "subnet", "create", "--network", "nope", "-l", "FIN-03") + if code := agentErrorCode(err); code != "NOT_FOUND" { + t.Errorf("code = %q (err %v), want NOT_FOUND", code, err) + } +} + +func TestSubnetCreateNoNetworks(t *testing.T) { + t.Parallel() + client := newFakeClient(t, newFakeAPI()) + _, _, err := runNetwork(t, agentFactory(client), "subnet", "create", "--network", "x", "-l", "FIN-03") + if code := agentErrorCode(err); code != "VALIDATION_ERROR" || !strings.Contains(err.Error(), "verda network create") { + t.Errorf("err = %v", err) + } +} + +func TestSubnetCreateReadsOnlyTheChosenNetwork(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + if _, _, err := runNetwork(t, agentFactory(client), "subnet", "create", "--network", "pn_a", "-l", "FIN-03"); err != nil { + t.Fatalf("create: %v", err) + } + for _, r := range api.requestsMatching("GET") { + if r.Path == "/private-networks/pn_b/subnets" { + t.Errorf("read the subnets of an unrelated network: %s", r.Path) + } + } +} + +func subnetData(api *fakeAPI) *subnetCreateData { + d := &subnetCreateData{networks: api.networks, subnets: api.subnets} + for _, l := range api.locations { + if l.IsPrivateNetworksEnabled { + d.locations = append(d.locations, l) + } + } + return d +} + +func runSubnetFlow(t *testing.T, opts *subnetCreateOptions, results ...wizard.TestResult) { + t.Helper() + engine := wizard.NewEngine(nil, nil, wizard.WithOutput(io.Discard), wizard.WithTestResults(results...)) + if err := engine.Run(context.Background(), buildSubnetCreateFlow(opts, subnetData(seededAPI()))); err != nil { + t.Fatalf("run: %v", err) + } +} + +func TestSubnetCreateFlowDefaults(t *testing.T) { + t.Parallel() + opts := &subnetCreateOptions{} + runSubnetFlow(t, opts, + wizard.SelectResult(1), // beta + wizard.SelectResult(0), // FIN-03 + wizard.TextResult(""), // name: default + wizard.TextResult(""), // CIDR: suggestion + // The default step is skipped: no default subnet in the location. + ) + if opts.Network != "pn_b" || opts.Location != "FIN-03" || opts.Name != "fin-03-1" || opts.CIDR != "10.0.0.0/24" || opts.Default || opts.defaultSet { + t.Errorf("opts = %+v", opts) + } +} + +func TestSubnetCreateFlowEditedCIDRAndDefault(t *testing.T) { + t.Parallel() + opts := &subnetCreateOptions{} + runSubnetFlow(t, opts, + wizard.SelectResult(0), // alpha (has FIN-03 already) + wizard.SelectResult(0), // FIN-03 + wizard.TextResult("web"), + wizard.TextResult("172.16.4.0/24"), + wizard.ConfirmResult(true), + ) + if opts.Network != "pn_a" || opts.Name != "web" || opts.CIDR != "172.16.4.0/24" || !opts.Default || !opts.defaultSet { + t.Errorf("opts = %+v", opts) + } +} + +func TestSubnetCreateFlowSkipsFlagStepsAndRecordsAnsweredFalse(t *testing.T) { + t.Parallel() + opts := &subnetCreateOptions{Network: "pn_a", Location: "US-SOUTHWEST-1", Name: "edge"} + runSubnetFlow(t, opts, + wizard.TextResult(""), + wizard.ConfirmResult(false), + ) + if opts.Name != "edge" || opts.CIDR != "10.0.2.0/24" || opts.Default || !opts.defaultSet { + t.Errorf("opts = %+v", opts) + } +} diff --git a/internal/verda-cli/cmd/network/subnet_delete.go b/internal/verda-cli/cmd/network/subnet_delete.go new file mode 100644 index 00000000..313b07f6 --- /dev/null +++ b/internal/verda-cli/cmd/network/subnet_delete.go @@ -0,0 +1,98 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +// NewCmdSubnetDelete creates the subnet delete command. +func NewCmdSubnetDelete(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command { + var networkArg string + var yes bool + cmd := &cobra.Command{ + Use: "delete []", + Aliases: []string{"rm"}, + Short: "Delete a subnet", + Long: cmdutil.LongDesc(` + Delete a subnet. The subnet must have no instances: delete them + first (verda vm action --action delete). The CLI never deletes + instances for you. A subnet ID needs --network. On a terminal, + with no subnet ID, the CLI shows a picker (of one network with + --network). + + Asks for confirmation. --yes skips the confirmation and is + required in agent mode. + `), + Example: cmdutil.Examples(` + verda network subnet delete $SUBNET_ID --network $NETWORK_ID + verda --agent network subnet delete $SUBNET_ID --network $NETWORK_ID --yes + `), + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runSubnetDelete(cmd, f, ioStreams, networkArg, args, yes) + }, + } + cmd.Flags().StringVar(&networkArg, flagNetwork, "", "Network ID (required with a subnet ID)") + cmd.Flags().BoolVarP(&yes, flagYes, "y", false, "Skip confirmation (required in agent mode)") + return cmd +} + +func runSubnetDelete(cmd *cobra.Command, f cmdutil.Factory, ioStreams cmdutil.IOStreams, networkArg string, args []string, yes bool) error { + if f.AgentMode() && !yes { + return cmdutil.NewConfirmationRequiredError("delete") + } + if err := checkSubnetArgs(f, networkArg, args); err != nil { + return err + } + client, err := f.VerdaClient() + if err != nil { + return err + } + networkID, subnet, err := resolveSubnetArg(cmd, f, ioStreams, client, networkArg, args) + if err != nil || subnet == nil { + return err + } + + if !yes { + ok, err := confirmDestructive(cmd.Context(), ioStreams, f.Prompter(), + fmt.Sprintf("Delete subnet %s (%s, %s, %s) of network %s", subnet.Name, subnet.ID, subnet.Location.Code, subnet.CIDR, networkID), + nil, + "Delete subnet "+subnet.Name+"?") + if err != nil { + return err + } + if !ok { + _, _ = fmt.Fprintln(ioStreams.ErrOut, canceledMsg) + return nil + } + } + + cmdutil.DebugJSON(ioStreams.ErrOut, f.Debug(), "Delete subnet:", map[string]string{"network_id": networkID, "id": subnet.ID, "name": subnet.Name}) + ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) + defer cancel() + err = cmdutil.RunWithSpinner(ctx, f.Status(), "Deleting subnet...", func(ctx context.Context) error { + return client.PrivateNetworks.DeleteSubnet(ctx, networkID, subnet.ID) + }) + if err != nil { + return err + } + return writeDeleted(ioStreams, f, "subnet", subnet.ID, subnet.Name) +} diff --git a/internal/verda-cli/cmd/network/subnet_delete_test.go b/internal/verda-cli/cmd/network/subnet_delete_test.go new file mode 100644 index 00000000..57facb7f --- /dev/null +++ b/internal/verda-cli/cmd/network/subnet_delete_test.go @@ -0,0 +1,142 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "encoding/json" + "strings" + "testing" + + tuitest "github.com/verda-cloud/verda-cli/pkg/tui/testing" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +func TestSubnetDeleteAgentRequiresYes(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + _, _, err := runNetwork(t, agentFactory(client), "subnet", "delete", "sn_a2") + if code := agentErrorCode(err); code != "CONFIRMATION_REQUIRED" { + t.Errorf("code = %q", code) + } + if len(api.requests) != 0 { + t.Errorf("no API call expected before --yes, got %v", api.requests) + } +} + +func TestSubnetDeleteConfirmed(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + out, errOut, err := runNetwork(t, tableFactory(client, tuitest.New().AddConfirm(true)), "subnet", "delete", "sn_a2", "--network", "pn_a") + if err != nil { + t.Fatalf("delete: %v", err) + } + for _, want := range []string{"Delete subnet us-1 (sn_a2, US-SOUTHWEST-1, 10.0.1.0/24) of network pn_a", "cannot be undone"} { + if !strings.Contains(errOut, want) { + t.Errorf("warning lacks %q:\n%s", want, errOut) + } + } + if d := api.requestsMatching("DELETE"); len(d) != 1 || d[0].Path != "/private-networks/pn_a/subnets/sn_a2" { + t.Errorf("DELETE = %v", d) + } + if !strings.Contains(out, "Deleted subnet us-1 (sn_a2)") { + t.Errorf("out = %q", out) + } +} + +func TestSubnetDeleteAgentYesWritesResult(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + out, _, err := runNetwork(t, agentFactory(client), "subnet", "rm", "sn_a1", "--network", "pn_a", "--yes") + if err != nil { + t.Fatalf("delete: %v", err) + } + var got map[string]string + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatalf("stdout is not JSON: %v\n%s", err, out) + } + if got["resource"] != "subnet" || got["id"] != "sn_a1" || got["status"] != "completed" { + t.Errorf("result = %v", got) + } + if d := api.requestsMatching("DELETE"); len(d) != 1 || d[0].Path != "/private-networks/pn_a/subnets/sn_a1" { + t.Errorf("DELETE = %v", d) + } +} + +func TestSubnetDeleteMissingArgOffTerminal(t *testing.T) { + t.Parallel() + api := seededAPI() + client := newFakeClient(t, api) + for _, args := range [][]string{{"subnet", "delete"}, {"subnet", "delete", "sn_a1"}} { + _, _, err := runNetwork(t, tableFactory(client, nil), args...) + if code := agentErrorCode(err); code != "MISSING_REQUIRED_FLAGS" { + t.Errorf("%v: code = %q (err %v), want MISSING_REQUIRED_FLAGS", args, code, err) + } + } + _, _, err := runNetwork(t, agentFactory(client), "subnet", "delete", "sn_a1", "--yes") + if code := agentErrorCode(err); code != "MISSING_REQUIRED_FLAGS" { + t.Errorf("agent: code = %q (err %v), want MISSING_REQUIRED_FLAGS", code, err) + } + if len(api.requests) != 0 { + t.Errorf("no API call expected without --network, got %v", api.requests) + } +} + +func TestUnknownIDIsNotFound(t *testing.T) { + t.Parallel() + client := newFakeClient(t, seededAPI()) + for _, args := range [][]string{ + {"subnet", "delete", "sn_nope", "--network", "pn_a", "--yes"}, + {"subnet", "list", "--network", "alpha"}, + } { + _, _, err := runNetwork(t, agentFactory(client), args...) + if code := agentErrorCode(err); code != "NOT_FOUND" { + t.Errorf("%v: code = %q (err %v), want NOT_FOUND", args, code, err) + } + } +} + +func TestSubnetDeletePicker(t *testing.T) { + withTerminal(t) + api := seededAPI() + client := newFakeClient(t, api) + out, _, err := runNetwork(t, tableFactory(client, tuitest.New().AddSelect(1).AddConfirm(true)), "subnet", "delete") + if err != nil { + t.Fatalf("delete: %v", err) + } + if !strings.Contains(out, "Deleted subnet us-1 (sn_a2)") { + t.Errorf("picker choice 1 should delete sn_a2: %q", out) + } +} + +func TestSubnetDeletePickerCancel(t *testing.T) { + withTerminal(t) + for name, p := range map[string]*cancelPrompter{ + "cancel row": {Prompter: tuitest.New().AddSelect(2)}, + "esc": {Prompter: tuitest.New(), selectErr: context.Canceled}, + } { + api := seededAPI() + client := newFakeClient(t, api) + f := &cmdutil.TestFactory{ClientOverride: client, OutputFormatOverride: outputTable, PrompterOverride: p} + out, errOut, err := runNetwork(t, f, "subnet", "delete") + if err != nil || out != "" || !strings.Contains(errOut, canceledMsg) || deletes(api) != 0 { + t.Errorf("%s: want %q on stderr only; out=%q stderr=%q err=%v deletes=%d", name, canceledMsg, out, errOut, err, deletes(api)) + } + } +} diff --git a/internal/verda-cli/cmd/network/subnet_list.go b/internal/verda-cli/cmd/network/subnet_list.go new file mode 100644 index 00000000..7b35e3a2 --- /dev/null +++ b/internal/verda-cli/cmd/network/subnet_list.go @@ -0,0 +1,108 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "context" + "fmt" + "strings" + "text/tabwriter" + + "github.com/spf13/cobra" + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +const noneMark = "-" + +// NewCmdSubnetList creates the subnet list command. +func NewCmdSubnetList(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command { + var networkArg, location string + cmd := &cobra.Command{ + Use: "list", + Aliases: []string{"ls"}, + Short: "List subnets of all networks, or of one", + Example: cmdutil.Examples(` + verda network subnet list + verda network subnet list --network $NETWORK_ID -l FIN-03 + verda network subnet ls -o json + `), + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return runSubnetList(cmd, f, ioStreams, networkArg, location) + }, + } + cmd.Flags().StringVar(&networkArg, flagNetwork, "", "Network ID (default: all networks)") + cmd.Flags().StringVarP(&location, flagLocation, "l", "", "Only subnets in this location, for example FIN-03") + return cmd +} + +func runSubnetList(cmd *cobra.Command, f cmdutil.Factory, ioStreams cmdutil.IOStreams, networkArg, location string) error { + client, err := f.VerdaClient() + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) + defer cancel() + rows, err := cmdutil.WithSpinner(ctx, f.Status(), "Loading subnets...", func(ctx context.Context) ([]subnetRow, error) { + return loadSubnetRows(ctx, client, networkArg) + }) + if err != nil { + return err + } + + if f.Debug() { + subnets := make([]verda.Subnet, 0, len(rows)) + for i := range rows { + subnets = append(subnets, rows[i].subnet) + } + cmdutil.DebugJSON(ioStreams.ErrOut, true, fmt.Sprintf("API response: %d subnet(s), before the location filter:", len(subnets)), subnets) + } + + views := make([]subnetView, 0, len(rows)) + names := map[string]string{} + for i := range rows { + if location != "" && !strings.EqualFold(rows[i].subnet.Location.Code, location) { + continue + } + views = append(views, newSubnetView(rows[i].network.ID, &rows[i].subnet)) + names[rows[i].network.ID] = rows[i].network.Name + } + + if wrote, err := cmdutil.WriteStructured(ioStreams.Out, f.OutputFormat(), views); wrote { + return err + } + if len(views) == 0 { + printNoSubnets(ioStreams) + return nil + } + + tw := tabwriter.NewWriter(ioStreams.Out, 0, 0, 2, ' ', 0) + _, _ = fmt.Fprintln(tw, "NETWORK\tNAME\tID\tLOCATION\tCIDR\tDEFAULT\tIPS USED/TOTAL\tROUTE") + for i := range views { + s := &views[i] + _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%d/%d\t%s\n", + names[s.NetworkID], s.Name, s.ID, s.Location, s.CIDR, defaultColumn(s.IsDefault), s.UsedIPCount, s.TotalIPCount, routeColumn(s.DefaultRouteInstance)) + } + return tw.Flush() +} + +func routeColumn(gw *attachedInstanceView) string { + if gw == nil { + return noneMark + } + return cmdutil.TextColumn(gw.Hostname) +} diff --git a/internal/verda-cli/cmd/network/subnet_list_test.go b/internal/verda-cli/cmd/network/subnet_list_test.go new file mode 100644 index 00000000..c885f5ac --- /dev/null +++ b/internal/verda-cli/cmd/network/subnet_list_test.go @@ -0,0 +1,66 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestSubnetListTableAllNetworks(t *testing.T) { + t.Parallel() + api := seededAPI() + api.addSubnet("pn_b", "sn_b1", "db", "FIN-03", "10.1.0.0/24", true) + client := newFakeClient(t, api) + out, _, err := runNetwork(t, tableFactory(client, nil), "subnet", "list") + if err != nil { + t.Fatalf("list: %v", err) + } + for _, want := range []string{"NETWORK", "IPS USED/TOTAL", "ROUTE", "alpha", "beta", "fin-03-1", "us-1", "db", "10.1.0.0/24", "1/251", "gw-1"} { + if !strings.Contains(out, want) { + t.Errorf("table lacks %q:\n%s", want, out) + } + } +} + +func TestSubnetListFilters(t *testing.T) { + t.Parallel() + client := newFakeClient(t, seededAPI()) + out, _, err := runNetwork(t, agentFactory(client), "subnets", "ls", "--network", "pn_a", "-l", "fin-03") + if err != nil { + t.Fatalf("list: %v", err) + } + var rows []map[string]any + if err := json.Unmarshal([]byte(out), &rows); err != nil { + t.Fatalf("not JSON: %v\n%s", err, out) + } + if len(rows) != 1 || rows[0]["id"] != "sn_a1" || rows[0]["network_id"] != "pn_a" { + t.Errorf("rows = %v", rows) + } +} + +func TestSubnetListEmpty(t *testing.T) { + t.Parallel() + client := newFakeClient(t, newFakeAPI()) + out, _, err := runNetwork(t, agentFactory(client), "subnet", "list") + if err != nil || strings.TrimSpace(out) != "[]" { + t.Errorf("agent: out = %q, err = %v", out, err) + } + out, errOut, err := runNetwork(t, tableFactory(client, nil), "subnet", "list") + if err != nil || !strings.Contains(out, "No subnets found.") || !strings.Contains(errOut, "Create one with: verda network subnet create") { + t.Errorf("table: out = %q, stderr = %q, err = %v", out, errOut, err) + } +} diff --git a/internal/verda-cli/cmd/network/views.go b/internal/verda-cli/cmd/network/views.go new file mode 100644 index 00000000..4245fa6d --- /dev/null +++ b/internal/verda-cli/cmd/network/views.go @@ -0,0 +1,92 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "time" + + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" +) + +// networkView is the JSON/YAML shape for one private network. +type networkView struct { + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Mode string `json:"mode" yaml:"mode"` + IsDefault bool `json:"is_default" yaml:"is_default"` + CreatedAt *time.Time `json:"created_at,omitempty" yaml:"created_at,omitempty"` +} + +func newNetworkView(n *verda.PrivateNetwork) networkView { + v := networkView{ID: n.ID, Name: n.Name, Mode: n.Mode, IsDefault: n.IsDefault} + if !n.CreatedAt.IsZero() { + created := n.CreatedAt + v.CreatedAt = &created + } + return v +} + +func newNetworkViews(networks []verda.PrivateNetwork) []networkView { + views := make([]networkView, len(networks)) + for i := range networks { + views[i] = newNetworkView(&networks[i]) + } + return views +} + +// attachedInstanceView is the JSON/YAML shape for the instance a subnet routes through. +type attachedInstanceView struct { + ID string `json:"id" yaml:"id"` + Hostname string `json:"hostname" yaml:"hostname"` + PrivateIP string `json:"private_ip,omitempty" yaml:"private_ip,omitempty"` + PublicIP *string `json:"public_ip,omitempty" yaml:"public_ip,omitempty"` + Status string `json:"status,omitempty" yaml:"status,omitempty"` +} + +// subnetView is the JSON/YAML shape for one subnet. NetworkID is not in the SDK +// subnet; callers pass the network the subnet was read from. +type subnetView struct { + ID string `json:"id" yaml:"id"` + NetworkID string `json:"network_id,omitempty" yaml:"network_id,omitempty"` + Name string `json:"name" yaml:"name"` + Location string `json:"location" yaml:"location"` + CIDR string `json:"cidr" yaml:"cidr"` + IsDefault bool `json:"is_default" yaml:"is_default"` + UsedIPCount int `json:"used_ip_count" yaml:"used_ip_count"` + TotalIPCount int `json:"total_ip_count" yaml:"total_ip_count"` + DefaultRouteInstance *attachedInstanceView `json:"default_route_instance,omitempty" yaml:"default_route_instance,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty" yaml:"created_at,omitempty"` +} + +func newSubnetView(networkID string, s *verda.Subnet) subnetView { + v := subnetView{ + ID: s.ID, + NetworkID: networkID, + Name: s.Name, + Location: s.Location.Code, + CIDR: s.CIDR, + IsDefault: s.IsDefault, + UsedIPCount: s.UsedIPCount, + TotalIPCount: s.TotalIPCount, + } + if a := s.DefaultRouteInstance; a != nil { + v.DefaultRouteInstance = &attachedInstanceView{ID: a.ID, Hostname: a.Hostname, PrivateIP: a.PrivateIP, PublicIP: a.PublicIP, Status: a.Status} + } + if !s.CreatedAt.IsZero() { + created := s.CreatedAt + v.CreatedAt = &created + } + return v +} diff --git a/internal/verda-cli/cmd/network/views_test.go b/internal/verda-cli/cmd/network/views_test.go new file mode 100644 index 00000000..57c6abe1 --- /dev/null +++ b/internal/verda-cli/cmd/network/views_test.go @@ -0,0 +1,39 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "bytes" + "strings" + "testing" + + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" +) + +func TestNetworkViewOmitsZeroCreatedAt(t *testing.T) { + t.Parallel() + v := newNetworkView(&verda.PrivateNetwork{ID: "pn_1", Name: "n", Mode: "custom"}) + for _, format := range []string{"json", "yaml"} { + var b bytes.Buffer + if _, err := cmdutil.WriteStructured(&b, format, v); err != nil { + t.Fatalf("%s: %v", format, err) + } + if out := b.String(); strings.Contains(out, "created_at") || strings.Contains(out, "0001-01-01") { + t.Errorf("%s carries a zero created_at: %s", format, out) + } + } +} diff --git a/internal/verda-cli/cmd/network/wizard.go b/internal/verda-cli/cmd/network/wizard.go new file mode 100644 index 00000000..582641e8 --- /dev/null +++ b/internal/verda-cli/cmd/network/wizard.go @@ -0,0 +1,213 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package network + +import ( + "errors" + "fmt" + "strings" + "unicode/utf8" + + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + "github.com/verda-cloud/verda-cli/pkg/tui/bubbletea" + "github.com/verda-cloud/verda-cli/pkg/tui/wizard" +) + +const maxNameLen = 64 + +var ( + errNameLength = fmt.Errorf("name must be 1-%d characters", maxNameLen) + errNameTaken = errors.New("the network already has a subnet with this name") +) + +func validateName(s string) error { + if s == "" || utf8.RuneCountInString(s) > maxNameLen { + return errNameLength + } + return nil +} + +func wizardLayout() []wizard.ViewDef { + return []wizard.ViewDef{ + {ID: "progress", View: wizard.NewProgressView(wizard.WithProgressPercent())}, + {ID: "hints", View: wizard.NewHintBarView(wizard.WithHintStyle(bubbletea.HintStyle()))}, + } +} + +func buildNetworkCreateFlow(opts *createOptions) *wizard.Flow { + return &wizard.Flow{ + Name: "network-create", + Layout: wizardLayout(), + Steps: []wizard.Step{ + stepNetworkName(opts), + stepNetworkMode(opts), + stepNetworkDefault(opts), + }, + } +} + +func stepNetworkName(opts *createOptions) wizard.Step { + return wizard.Step{ + Name: flagName, + Description: "Network name", + Prompt: wizard.TextInputPrompt, + Required: true, + Validate: func(v any) error { return validateName(strings.TrimSpace(v.(string))) }, + Setter: func(v any) { opts.Name = strings.TrimSpace(v.(string)) }, + Resetter: func() { opts.Name = "" }, + IsSet: func() bool { return opts.Name != "" }, + Value: func() any { return opts.Name }, + } +} + +func stepNetworkMode(opts *createOptions) wizard.Step { + return wizard.Step{ + Name: flagMode, + Description: "Subnet mode", + Prompt: wizard.SelectPrompt, + Required: true, + Loader: wizard.StaticChoices( + wizard.Choice{Label: "Custom", Value: verda.NetworkModeCustom, Description: "You create the subnets yourself"}, + wizard.Choice{Label: "Auto", Value: verda.NetworkModeAuto, Description: "As the default network, a deploy with no subnet gets one in its location"}, + ), + Default: func(_ map[string]any) any { return verda.NetworkModeCustom }, + Setter: func(v any) { opts.Mode = v.(string) }, + Resetter: func() { opts.Mode = verda.NetworkModeCustom }, + IsSet: func() bool { return opts.modeSet }, + Value: func() any { return opts.Mode }, + } +} + +func stepNetworkDefault(opts *createOptions) wizard.Step { + return wizard.Step{ + Name: flagDefault, + Description: "Make it the default network? (VMs that name no network join it)", + Prompt: wizard.ConfirmPrompt, + Default: func(_ map[string]any) any { return false }, + Setter: func(v any) { + b, _ := v.(bool) + opts.Default = b + }, + Resetter: func() { opts.Default = false }, + IsSet: func() bool { return opts.defaultSet }, + Value: func() any { return opts.Default }, + } +} + +// Flags skip their steps. +func buildSubnetCreateFlow(opts *subnetCreateOptions, data *subnetCreateData) *wizard.Flow { + networkSet, locationSet := opts.Network != "", opts.Location != "" + nameSet, cidrSet, defaultSet := opts.Name != "", opts.CIDR != "", opts.defaultSet + return &wizard.Flow{ + Name: "subnet-create", + Layout: wizardLayout(), + Steps: []wizard.Step{ + { + Name: flagNetwork, + Description: "Private network", + Prompt: wizard.SelectPrompt, + Required: true, + Loader: wizard.StaticChoices(networkChoices(data.networks)...), + Default: func(_ map[string]any) any { + if n := defaultNetwork(data.networks); n != nil { + return n.ID + } + return "" + }, + Setter: func(v any) { opts.Network, _ = v.(string) }, + Resetter: func() { opts.Network = "" }, + IsSet: func() bool { return networkSet }, + Value: func() any { return opts.Network }, + }, + { + Name: flagLocation, + Description: "Location (only locations with private networks)", + Prompt: wizard.SelectPrompt, + Required: true, + Loader: wizard.StaticChoices(locationChoices(data.locations)...), + Setter: func(v any) { opts.Location, _ = v.(string) }, + Resetter: func() { opts.Location = "" }, + IsSet: func() bool { return locationSet }, + Value: func() any { return opts.Location }, + }, + { + Name: flagName, + Description: "Subnet name", + Prompt: wizard.TextInputPrompt, + DependsOn: []string{flagNetwork, flagLocation}, + Default: func(_ map[string]any) any { return data.defaultName(opts.Network, opts.Location) }, + Validate: func(v any) error { return data.checkName(opts.Network, strings.TrimSpace(v.(string))) }, + Setter: func(v any) { opts.Name = strings.TrimSpace(v.(string)) }, + Resetter: func() { opts.Name = "" }, + IsSet: func() bool { return nameSet }, + Value: func() any { return opts.Name }, + }, + { + Name: flagCIDR, + Description: "IPv4 range (CIDR)", + Prompt: wizard.TextInputPrompt, + DependsOn: []string{flagNetwork}, + Default: func(_ map[string]any) any { + if p, err := data.suggestCIDR(opts.Network); err == nil { + return p.String() + } + return "" + }, + Validate: func(v any) error { return checkCIDRFormat(strings.TrimSpace(v.(string))) }, + Setter: func(v any) { opts.CIDR = strings.TrimSpace(v.(string)) }, + Resetter: func() { opts.CIDR = "" }, + IsSet: func() bool { return cidrSet }, + Value: func() any { return opts.CIDR }, + }, + { + Name: flagDefault, + Description: "Make it the default subnet of this location?", + Prompt: wizard.ConfirmPrompt, + DependsOn: []string{flagNetwork, flagLocation}, + // The engine resets a skipped step, so never skip a --default flag. + ShouldSkip: func(_ map[string]any) bool { return !defaultSet && data.noDefaultIn(opts.Network, opts.Location) }, + Default: func(_ map[string]any) any { return false }, + Setter: func(v any) { + opts.Default, _ = v.(bool) + opts.defaultSet = true + }, + Resetter: func() { opts.Default, opts.defaultSet = false, false }, + IsSet: func() bool { return defaultSet }, + Value: func() any { return opts.Default }, + }, + }, + } +} + +func networkChoices(networks []verda.PrivateNetwork) []wizard.Choice { + choices := make([]wizard.Choice, len(networks)) + for i := range networks { + desc := networks[i].ID + ", " + networks[i].Mode + if networks[i].IsDefault { + desc += ", default" + } + choices[i] = wizard.Choice{Label: networks[i].Name, Value: networks[i].ID, Description: desc} + } + return choices +} + +func locationChoices(locations []verda.Location) []wizard.Choice { + choices := make([]wizard.Choice, len(locations)) + for i := range locations { + choices[i] = wizard.Choice{Label: locations[i].Code, Value: locations[i].Code, Description: locations[i].Name} + } + return choices +} diff --git a/tests/integration/network_test.go b/tests/integration/network_test.go new file mode 100644 index 00000000..612bade2 --- /dev/null +++ b/tests/integration/network_test.go @@ -0,0 +1,32 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build integration + +package integration + +import "testing" + +// Reads only: the real API's network and subnet lists decode into the CLI's JSON shape. +func TestNetwork_ListsAreJSON(t *testing.T) { + requireProfile(t, "test") + for _, args := range [][]string{{"network", "list"}, {"network", "subnet", "list"}} { + r := runAgent(t, "test", args...) + if r.ExitCode != 0 { + t.Skipf("%v: exit %d (private networks may be unavailable to [test]): %s", args, r.ExitCode, r.Stderr) + } + var rows []map[string]any + parseJSON(t, r, &rows) + } +}