From e145d1bf82ca0769440828ef558e2a48426e4424 Mon Sep 17 00:00:00 2001 From: Francisco Serrano Date: Thu, 24 Sep 2026 11:24:36 +0300 Subject: [PATCH 1/7] feat: add v9 client plumbing --- go.mod | 11 +++++-- go.sum | 40 ++++++++++++++++------- internal/commands/executor.go | 13 ++++++++ internal/commands/executor_test.go | 10 ++++++ internal/commands/runcommand.go | 6 ++++ internal/config/config.go | 51 ++++++++++++++++++++++++++++++ 6 files changed, 116 insertions(+), 15 deletions(-) diff --git a/go.mod b/go.mod index 569fe257d..65f44803f 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/UpCloudLtd/progress v1.2.1 github.com/UpCloudLtd/upcloud-go-api/credentials v0.1.1 github.com/UpCloudLtd/upcloud-go-api/v8 v8.40.0 + github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260917090650-3e1a69f90c36 github.com/adrg/xdg v0.5.3 github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 github.com/jedib0t/go-pretty/v6 v6.7.9 @@ -42,6 +43,7 @@ require ( github.com/Masterminds/sprig/v3 v3.3.0 // indirect github.com/Masterminds/squirrel v1.5.4 // indirect github.com/UpCloudLtd/httplog v0.0.0-20260624214043-23b0cab8e085 // indirect + github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect github.com/blang/semver/v4 v4.0.0 // indirect github.com/chai2010/gettext-go v1.0.2 // indirect github.com/containerd/containerd v1.7.30 // indirect @@ -61,9 +63,10 @@ require ( github.com/go-errors/errors v1.4.2 // indirect github.com/go-gorp/gorp/v3 v3.1.0 // indirect github.com/go-logr/logr v1.4.3 // indirect - github.com/go-openapi/jsonpointer v0.21.0 // indirect + github.com/go-openapi/jsonpointer v0.23.1 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.23.0 // indirect + github.com/go-openapi/swag/jsonname v0.26.0 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/gobwas/glob v0.2.3 // indirect github.com/godbus/dbus/v5 v5.2.2 // indirect @@ -88,7 +91,7 @@ require ( github.com/lib/pq v1.10.9 // indirect github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect github.com/mailru/easyjson v0.7.7 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-runewidth v0.0.16 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/go-wordwrap v1.0.1 // indirect @@ -100,6 +103,8 @@ require ( github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect + github.com/oapi-codegen/oapi-codegen/v2 v2.8.0 // indirect + github.com/oapi-codegen/runtime v1.6.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.1 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect @@ -125,7 +130,7 @@ require ( golang.org/x/oauth2 v0.30.0 // indirect golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.40.0 // indirect - golang.org/x/time v0.12.0 // indirect + golang.org/x/time v0.14.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250528174236-200df99c418a // indirect google.golang.org/grpc v1.72.2 // indirect google.golang.org/protobuf v1.36.8 // indirect diff --git a/go.sum b/go.sum index 48c7fd9d6..2f5a7f30e 100644 --- a/go.sum +++ b/go.sum @@ -22,6 +22,7 @@ github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0= github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM= github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10= +github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= github.com/UpCloudLtd/httplog v0.0.0-20260624214043-23b0cab8e085 h1:WKK9DZI0ZQikQjhHk+/X2HWKxFrENOvseaDysZE8nPs= github.com/UpCloudLtd/httplog v0.0.0-20260624214043-23b0cab8e085/go.mod h1:79ZjkJrYkl540hQ5Fy7XkRfR7109HGMTzHdVEkynTqw= github.com/UpCloudLtd/progress v1.2.1 h1:ljLJW2pn3KgmUgk7jxgHk5Ux/8so4eJkXJGtOw9EAPo= @@ -30,8 +31,12 @@ github.com/UpCloudLtd/upcloud-go-api/credentials v0.1.1 h1:eTfQsv58ufALOk9BZ7WbS github.com/UpCloudLtd/upcloud-go-api/credentials v0.1.1/go.mod h1:7OtVs2UqtfvjkC1HfE+Oud0MnbMv7qUWnbEgxnTAqts= github.com/UpCloudLtd/upcloud-go-api/v8 v8.40.0 h1:MvG4zuzKb0WXruxDebF1OgFXZ+zxPH2MBa0jHDQ9dBo= github.com/UpCloudLtd/upcloud-go-api/v8 v8.40.0/go.mod h1:ex/UPAIOJxtzwe0DqX2gwCC2/oce7pBqg78pB+YnH9k= +github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260917090650-3e1a69f90c36 h1:VCwOEnq3lUKWeAg9BFejef48BlFUwcjO6UmOINgkxtg= +github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260917090650-3e1a69f90c36/go.mod h1:mHX52YNu+cWHzK7fNoT0g5TOzbVxgnfWZtJdWuhKHgs= github.com/adrg/xdg v0.5.3 h1:xRnxJXne7+oWDatRhR1JLnvuccuIeCoBu2rtuLqQB78= github.com/adrg/xdg v0.5.3/go.mod h1:nlTsY+NNiCBGCK2tpm09vRqfVzrc2fLmXGpBLF0zlTQ= +github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= +github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= @@ -40,6 +45,7 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= +github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= github.com/bradleyjkemp/cupaloy/v2 v2.8.0 h1:any4BmKE+jGIaMpnU8YgH/I2LPiLBufr6oMMlVBbn9M= github.com/bradleyjkemp/cupaloy/v2 v2.8.0/go.mod h1:bm7JXdkRd4BHJk9HpwqAI8BoAY1lps46Enkdqw6aRX0= github.com/bshuster-repo/logrus-logstash-hook v1.0.0 h1:e+C0SB5R1pu//O4MQ3f9cFuPGoOVeF2fE4Og9otCc70= @@ -117,13 +123,17 @@ github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ4 github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= -github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= -github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= +github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4= +github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY= github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= +github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w= +github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M= +github.com/go-openapi/testify/v2 v2.4.2 h1:tiByHpvE9uHrrKjOszax7ZvKB7QOgizBWGBLuq0ePx4= +github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= @@ -182,6 +192,7 @@ github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8Hm github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= @@ -204,11 +215,10 @@ github.com/m7shapan/cidr v0.0.0-20200427124835-7eba0889a5d2/go.mod h1:DMBq1OXADd github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= @@ -239,6 +249,12 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f h1:y5//uYreIhSUg3J1GEMiLbxo1LJaP8RfCpH6pymGZus= github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= +github.com/oapi-codegen/nullable v1.1.0 h1:eAh8JVc5430VtYVnq00Hrbpag9PFRGWLjxR1/3KntMs= +github.com/oapi-codegen/nullable v1.1.0/go.mod h1:KUZ3vUzkmEKY90ksAmit2+5juDIhIZhfDl+0PwOQlFY= +github.com/oapi-codegen/oapi-codegen/v2 v2.8.0 h1:s4hxMxuqtR8jPzXkBTtFwY/SBuj3gEAYikmbBSdtLMM= +github.com/oapi-codegen/oapi-codegen/v2 v2.8.0/go.mod h1:yae2TI9IYB5vxQ35gFrpXh9L5H1eJv4MAUK1jumGMTo= +github.com/oapi-codegen/runtime v1.6.0 h1:7Xx+GlueD6nRuyKoCPzL434Jfi3BetbiJOrzCHp/VPU= +github.com/oapi-codegen/runtime v1.6.0/go.mod h1:GwV7hC2hviaMzj+ITfHVRESK5J2W/GefVwIND/bMGvU= github.com/onsi/ginkgo/v2 v2.27.2 h1:LzwLj0b89qtIy6SSASkzlNvX6WktqurSHwkk2ipF/Ns= github.com/onsi/ginkgo/v2 v2.27.2/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A= @@ -306,6 +322,7 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= +github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -383,8 +400,8 @@ 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/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= -golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= -golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= @@ -396,17 +413,16 @@ golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= -golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= -golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= -golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= -golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= +golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= +golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= google.golang.org/genproto v0.0.0-20231211222908-989df2bf70f3 h1:1hfbdAfFbkmpg41000wDVqr7jUpK/Yo+LPnIxxGzmkg= google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb h1:p31xT4yrYrSM/G4Sn2+TNUkVhFCbG9y8itM2S6Th950= google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb/go.mod h1:jbe3Bkdp+Dh2IrslsFCklNhweNTBgSYanP1UXhJDhKg= diff --git a/internal/commands/executor.go b/internal/commands/executor.go index ece19b779..2f5fa0b67 100644 --- a/internal/commands/executor.go +++ b/internal/commands/executor.go @@ -16,6 +16,7 @@ import ( internal "github.com/UpCloudLtd/upcloud-cli/v3/internal/service" "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/service" + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" ) // Executor represents the execution context for commands @@ -35,9 +36,11 @@ type Executor interface { Account() service.Account Token() service.Token All() internal.AllServices + V9() *upcloudv9.ClientWithResponses Debug(msg string, args ...any) WithLogger(args ...any) Executor WithProgress(progress *progress.Progress) Executor + WithV9Client(client *upcloudv9.ClientWithResponses) Executor } type executeResult struct { @@ -51,6 +54,7 @@ type executorImpl struct { Config *config.Config progress *progress.Progress service internal.AllServices + v9Client *upcloudv9.ClientWithResponses logger *slog.Logger sigIntChan chan os.Signal } @@ -65,6 +69,11 @@ func (e executorImpl) WithProgress(progress *progress.Progress) Executor { return &e } +func (e executorImpl) WithV9Client(client *upcloudv9.ClientWithResponses) Executor { + e.v9Client = client + return &e +} + func (e *executorImpl) Context() context.Context { return e.Config.Context() } @@ -152,6 +161,10 @@ func (e executorImpl) All() internal.AllServices { return e.service } +func (e executorImpl) V9() *upcloudv9.ClientWithResponses { + return e.v9Client +} + // NewExecutor creates the default Executor func NewExecutor(cfg *config.Config, svc internal.AllServices, logger *slog.Logger) Executor { executor := &executorImpl{ diff --git a/internal/commands/executor_test.go b/internal/commands/executor_test.go index 0bcc57317..fea478a6f 100644 --- a/internal/commands/executor_test.go +++ b/internal/commands/executor_test.go @@ -8,9 +8,19 @@ import ( "github.com/UpCloudLtd/upcloud-cli/v3/internal/config" smock "github.com/UpCloudLtd/upcloud-cli/v3/internal/mock" + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" "github.com/stretchr/testify/assert" ) +func TestExecutor_V9Client(t *testing.T) { + mService := &smock.Service{} + cfg := config.New() + v9Client := &upcloudv9.ClientWithResponses{} + exec := NewExecutor(cfg, mService, cfg.NewLogger("test")).WithV9Client(v9Client) + + assert.Same(t, v9Client, exec.V9()) +} + func TestExecutor_WaitFor(t *testing.T) { mService := &smock.Service{} cfg := config.New() diff --git a/internal/commands/runcommand.go b/internal/commands/runcommand.go index b32a33d38..d9be3bb59 100644 --- a/internal/commands/runcommand.go +++ b/internal/commands/runcommand.go @@ -17,6 +17,12 @@ func commandRunE(command Command, service internal.AllServices, config *config.C logger := config.NewLogger("runcommand") cmdLogger := logger.With("command", command.Cobra().CommandPath()) executor := NewExecutor(config, service, cmdLogger) + v9Client, err := config.CreateV9Client() + if err != nil { + cmdLogger.Debug("cannot create v9 SDK client", "error", err) + } else { + executor = executor.WithV9Client(v9Client) + } w := command.Cobra().OutOrStdout() diff --git a/internal/config/config.go b/internal/config/config.go index b1237995b..ead3736b7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log/slog" + "net/http" "os" "path/filepath" "regexp" @@ -18,6 +19,7 @@ import ( "github.com/UpCloudLtd/upcloud-go-api/credentials" "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/client" "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/service" + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" "github.com/adrg/xdg" "github.com/spf13/pflag" "github.com/spf13/viper" @@ -250,6 +252,55 @@ func (s *Config) CreateService() (internal.AllServices, error) { return svc, nil } +func (s *Config) CreateV9Client() (*upcloudv9.ClientWithResponses, error) { + username := s.GetString("username") + password := s.GetString("password") + token := s.GetString("token") + + if token == "" && (username == "" || password == "") { + configDetails := fmt.Sprintf("default location %s", filepath.Join(xdg.ConfigHome, "upctl.yaml")) + if s.GetString("config") != "" { + configDetails = fmt.Sprintf("used %s", s.GetString("config")) + } + return nil, clierrors.MissingCredentialsError{ConfigFile: configDetails, ServiceName: credentials.KeyringServiceName} + } + + apiLogger := s.NewLogger("api") + httpClient := client.NewDefaultHTTPClient() + httpClient.Timeout = s.ClientTimeout() + if os.Getenv(upcloudv9.EnvDebugSkipCertificateVerify) == "1" { + transport := httpClient.Transport.(*http.Transport).Clone() + transport.TLSClientConfig = transport.TLSClientConfig.Clone() + transport.TLSClientConfig.InsecureSkipVerify = true //nolint:gosec + httpClient.Transport = transport + } + + options := []upcloudv9.ClientOption{ + upcloudv9.WithHTTPClient(httpClient), + upcloudv9.WithLogger(func(_ context.Context, msg string, args ...any) { + apiLogger.Debug(msg, args...) + }), + } + if token != "" { + options = append(options, upcloudv9.WithCredentials(credentials.Credentials{Token: token})) + } else { + options = append(options, upcloudv9.WithCredentials(credentials.Credentials{Username: username, Password: password})) + } + if baseURL := os.Getenv(upcloudv9.EnvDebugAPIBaseURL); baseURL != "" { + options = append(options, upcloudv9.WithBaseURL(baseURL)) + } + + v9Client, err := upcloudv9.NewClientWithResponses(upcloudv9.ServerUrlHttpsapiUpcloudCom, options...) + if err != nil { + return nil, err + } + v9Client.RequestEditors = append(v9Client.RequestEditors, func(_ context.Context, req *http.Request) error { + req.Header.Set("User-Agent", fmt.Sprintf("upctl/%s", GetVersion())) + return nil + }) + return v9Client, nil +} + func GetVersion() string { version := getVersion() re := regexp.MustCompile(`v[0-9]+\.[0-9]+\.[0-9]+.*`) From 88b10abe7ae58cd7d5b12584809da6bab583b018 Mon Sep 17 00:00:00 2001 From: Francisco Serrano Date: Thu, 24 Sep 2026 11:43:20 +0300 Subject: [PATCH 2/7] fix: linter error --- internal/config/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/config/config.go b/internal/config/config.go index ead3736b7..55dea9af9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -271,7 +271,7 @@ func (s *Config) CreateV9Client() (*upcloudv9.ClientWithResponses, error) { if os.Getenv(upcloudv9.EnvDebugSkipCertificateVerify) == "1" { transport := httpClient.Transport.(*http.Transport).Clone() transport.TLSClientConfig = transport.TLSClientConfig.Clone() - transport.TLSClientConfig.InsecureSkipVerify = true //nolint:gosec + transport.TLSClientConfig.InsecureSkipVerify = true httpClient.Transport = transport } From 9ea29742ac9f4fb7f1c2fb7ef433c4635c5b241d Mon Sep 17 00:00:00 2001 From: Francisco Serrano Date: Tue, 29 Sep 2026 19:04:24 +0300 Subject: [PATCH 3/7] feat(database): migrate CRUD operations to v9 SDK --- CHANGELOG.md | 19 + go.mod | 4 +- go.sum | 2 + internal/apierror/apierror.go | 83 ++++ internal/apierror/apierror_test.go | 75 ++++ internal/clierrors/invalid_credentials.go | 15 +- .../clierrors/invalid_credentials_test.go | 30 ++ internal/commands/database/create.go | 327 ++++++++++---- internal/commands/database/create_test.go | 412 +++++++++++------- internal/commands/database/database.go | 20 +- internal/commands/database/delete.go | 51 ++- internal/commands/database/delete_test.go | 122 +++++- internal/commands/database/fakeapi_test.go | 97 +++++ internal/commands/database/list.go | 33 +- internal/commands/database/list_test.go | 74 +++- internal/commands/database/plans.go | 12 +- internal/commands/database/plans_test.go | 38 +- internal/commands/database/show.go | 157 ++++--- internal/commands/database/show_test.go | 149 ++++++- internal/commands/database/v9.go | 154 +++++++ internal/commands/database/v9_test.go | 91 ++++ internal/commands/stack/starterkit/deploy.go | 2 +- internal/format/database.go | 5 +- internal/labels/output.go | 10 +- internal/labels/process.go | 9 +- internal/mockexecute/mockexecute.go | 11 +- internal/paging/paging.go | 6 + internal/utils/errors.go | 5 + internal/utils/errors_test.go | 31 ++ 29 files changed, 1641 insertions(+), 403 deletions(-) create mode 100644 internal/apierror/apierror.go create mode 100644 internal/apierror/apierror_test.go create mode 100644 internal/clierrors/invalid_credentials_test.go create mode 100644 internal/commands/database/fakeapi_test.go create mode 100644 internal/commands/database/v9.go create mode 100644 internal/commands/database/v9_test.go create mode 100644 internal/utils/errors_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 313242d4d..40977f760 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Add `--plan-compute`, `--plan-node-count`, `--plan-storage-gib`, and `--plan-backups` flags to `database create` for selecting PostgreSQL and MySQL plans by their components. Run `upctl database plans ` to list valid values. + +### Changed + +- `database create`, `database list`, `database show`, and `database delete` use the v9 SDK. The JSON and YAML output of `database create`, `database list`, and `database show` follows the v9 API response shape. +- `database show` displays the plan components of componentised plans. +- `database create` without a plan flag now creates PostgreSQL and MySQL databases with the `--plan-*` defaults instead of the `2x2xCPU-4GB-100GB` plan: `rdb.standard.2CPU-8GB` compute with 8 GB memory per node instead of 4 GB, 2 nodes, 100 GiB storage per node, and the `regular` backup tier instead of the legacy backup retention of 8 days for MySQL and 15 days for PostgreSQL. +- `database create`: `--plan` is deprecated for PostgreSQL and MySQL, and it cannot be combined with the `--plan-*` flags. `--plan` no longer has a default, and it is required for database types other than PostgreSQL and MySQL. +- `database create`: `--maintenance-dow` and `--maintenance-time` must be used together. + +### Fixed + +- Fix `database plans` returning no plans for OpenSearch and Valkey unless `--show-legacy` was set. Engines without componentised plans now show their normal plan catalog by default. +- Fix the termination protection flag in the `database create` example. +- Fix `database plans --show-legacy` showing legacy plan memory and storage in MB instead of GB. +- Fix `database create` sending string properties, such as `version`, as numbers when the value looks like a number. + ## [3.36.0] - 2026-07-28 ### Added diff --git a/go.mod b/go.mod index 65f44803f..ed823c5e5 100644 --- a/go.mod +++ b/go.mod @@ -7,9 +7,10 @@ require ( github.com/UpCloudLtd/progress v1.2.1 github.com/UpCloudLtd/upcloud-go-api/credentials v0.1.1 github.com/UpCloudLtd/upcloud-go-api/v8 v8.40.0 - github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260917090650-3e1a69f90c36 + github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260929151619-56d6c5385c88 github.com/adrg/xdg v0.5.3 github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 + github.com/google/uuid v1.6.0 github.com/jedib0t/go-pretty/v6 v6.7.9 github.com/joho/godotenv v1.5.1 github.com/m7shapan/cidr v0.0.0-20200427124835-7eba0889a5d2 @@ -74,7 +75,6 @@ require ( github.com/google/btree v1.1.3 // indirect github.com/google/gnostic-models v0.7.0 // indirect github.com/google/go-cmp v0.7.0 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect github.com/gosuri/uitable v0.0.4 // indirect github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect diff --git a/go.sum b/go.sum index 2f5a7f30e..98c0dcd1f 100644 --- a/go.sum +++ b/go.sum @@ -33,6 +33,8 @@ github.com/UpCloudLtd/upcloud-go-api/v8 v8.40.0 h1:MvG4zuzKb0WXruxDebF1OgFXZ+zxP github.com/UpCloudLtd/upcloud-go-api/v8 v8.40.0/go.mod h1:ex/UPAIOJxtzwe0DqX2gwCC2/oce7pBqg78pB+YnH9k= github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260917090650-3e1a69f90c36 h1:VCwOEnq3lUKWeAg9BFejef48BlFUwcjO6UmOINgkxtg= github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260917090650-3e1a69f90c36/go.mod h1:mHX52YNu+cWHzK7fNoT0g5TOzbVxgnfWZtJdWuhKHgs= +github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260929151619-56d6c5385c88 h1:9L2gEK8MvxPkko0/ZYI8Ysx+F3fje/pWT044KQ6prbY= +github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260929151619-56d6c5385c88/go.mod h1:mHX52YNu+cWHzK7fNoT0g5TOzbVxgnfWZtJdWuhKHgs= github.com/adrg/xdg v0.5.3 h1:xRnxJXne7+oWDatRhR1JLnvuccuIeCoBu2rtuLqQB78= github.com/adrg/xdg v0.5.3/go.mod h1:nlTsY+NNiCBGCK2tpm09vRqfVzrc2fLmXGpBLF0zlTQ= github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= diff --git a/internal/apierror/apierror.go b/internal/apierror/apierror.go new file mode 100644 index 000000000..561243615 --- /dev/null +++ b/internal/apierror/apierror.go @@ -0,0 +1,83 @@ +// Package apierror provides the CLI's own error type for UpCloud API errors, independent of the SDK version. +package apierror + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "strings" +) + +// Problem is an UpCloud API error. Its Error and ErrorCode output match the v8 SDK's upcloud.Problem. +type Problem struct { + Type string `json:"type"` + Title string `json:"title"` + InvalidParams []InvalidParam `json:"invalid_params,omitempty"` + CorrelationID string `json:"correlation_id,omitempty"` + Status int `json:"status"` +} + +type InvalidParam struct { + Name string `json:"name"` + Reason string `json:"reason"` +} + +func (p *Problem) Error() string { + var sb strings.Builder + _, _ = fmt.Fprintf(&sb, "%s (type=%s, status=%d", p.Title, p.Type, p.Status) + if p.CorrelationID != "" { + _, _ = fmt.Fprintf(&sb, ", correlation_id=%s", p.CorrelationID) + } + for _, ip := range p.InvalidParams { + _, _ = fmt.Fprintf(&sb, ", invalid_params_%s='%s'", ip.Name, ip.Reason) + } + sb.WriteString(")") + return sb.String() +} + +// ErrorCode returns the error code, e.g. SERVICE_NOT_FOUND, also when Type is a documentation URL. +func (p *Problem) ErrorCode() string { + parsedURL, err := url.Parse(p.Type) + if err != nil || parsedURL.Scheme == "" || parsedURL.Host == "" { + return p.Type + } + return strings.Replace(parsedURL.Fragment, "ERROR_", "", 1) +} + +// FromResponse converts an unsuccessful API response into a *Problem. It accepts problem+json and legacy error bodies. +func FromResponse(status int, body []byte) error { + if status >= 200 && status < 300 { + return fmt.Errorf("unexpected API response (status %d)", status) + } + + prob := &Problem{} + if json.Unmarshal(body, prob) == nil && prob.Title != "" { + if prob.Status == 0 { + prob.Status = status + } + return prob + } + + legacy := struct { + Error struct { + ErrorCode string `json:"error_code"` + ErrorMessage string `json:"error_message"` + } `json:"error"` + }{} + if json.Unmarshal(body, &legacy) == nil && legacy.Error.ErrorCode != "" { + return &Problem{Type: legacy.Error.ErrorCode, Title: legacy.Error.ErrorMessage, Status: status} + } + + title := strings.TrimSpace(string(body)) + if title == "" { + title = http.StatusText(status) + } + return &Problem{Title: title, Status: status} +} + +func IsNotFound(err error) bool { + var prob *Problem + return errors.As(err, &prob) && prob.Status == http.StatusNotFound +} diff --git a/internal/apierror/apierror_test.go b/internal/apierror/apierror_test.go new file mode 100644 index 000000000..98f339645 --- /dev/null +++ b/internal/apierror/apierror_test.go @@ -0,0 +1,75 @@ +package apierror + +import ( + "net/http" + "testing" + + "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestFromResponse(t *testing.T) { + for _, test := range []struct { + name string + status int + body string + expected Problem + }{ + { + name: "problem details", + status: http.StatusBadRequest, + body: `{"type": "https://developers.upcloud.com/1.3/errors#ERROR_INVALID_REQUEST", "title": "Invalid request", "status": 400, "correlation_id": "abc", "invalid_params": [{"name": "plan", "reason": "unknown"}]}`, + expected: Problem{Type: "https://developers.upcloud.com/1.3/errors#ERROR_INVALID_REQUEST", Title: "Invalid request", Status: 400, CorrelationID: "abc", InvalidParams: []InvalidParam{{Name: "plan", Reason: "unknown"}}}, + }, + { + name: "problem details without status", + status: http.StatusConflict, + body: `{"type": "conflict", "title": "Conflict"}`, + expected: Problem{Type: "conflict", Title: "Conflict", Status: http.StatusConflict}, + }, + { + name: "legacy error", + status: http.StatusNotFound, + body: `{"error": {"error_code": "SERVICE_NOT_FOUND", "error_message": "Service not found"}}`, + expected: Problem{Type: "SERVICE_NOT_FOUND", Title: "Service not found", Status: http.StatusNotFound}, + }, + { + name: "plain text", + status: http.StatusBadGateway, + body: "bad gateway\n", + expected: Problem{Title: "bad gateway", Status: http.StatusBadGateway}, + }, + { + name: "empty body", + status: http.StatusServiceUnavailable, + expected: Problem{Title: "Service Unavailable", Status: http.StatusServiceUnavailable}, + }, + } { + t.Run(test.name, func(t *testing.T) { + err := FromResponse(test.status, []byte(test.body)) + var problem *Problem + require.ErrorAs(t, err, &problem) + assert.Equal(t, test.expected, *problem) + assert.Equal(t, test.status == http.StatusNotFound, IsNotFound(err)) + }) + } + + assert.EqualError(t, FromResponse(http.StatusOK, nil), "unexpected API response (status 200)") +} + +// Users must see the same messages and error codes as with the v8 SDK error type. +func TestProblem_MatchesV8(t *testing.T) { + for _, p := range []Problem{ + {Type: "https://developers.upcloud.com/1.3/errors#ERROR_AUTHENTICATION_FAILED", Title: "Authentication failed", Status: 401}, + {Type: "SERVICE_NOT_FOUND", Title: "Service not found", Status: 404, CorrelationID: "abc"}, + {Type: "invalid", Title: "Invalid", Status: 400, InvalidParams: []InvalidParam{{Name: "plan", Reason: "unknown"}, {Name: "zone", Reason: "missing"}}}, + } { + v8 := upcloud.Problem{Type: p.Type, Title: p.Title, Status: p.Status, CorrelationID: p.CorrelationID} + for _, ip := range p.InvalidParams { + v8.InvalidParams = append(v8.InvalidParams, upcloud.ProblemInvalidParam{Name: ip.Name, Reason: ip.Reason}) + } + assert.Equal(t, v8.Error(), p.Error()) + assert.Equal(t, v8.ErrorCode(), p.ErrorCode()) + } +} diff --git a/internal/clierrors/invalid_credentials.go b/internal/clierrors/invalid_credentials.go index 51621c35b..896fa4d9d 100644 --- a/internal/clierrors/invalid_credentials.go +++ b/internal/clierrors/invalid_credentials.go @@ -3,6 +3,7 @@ package clierrors import ( "errors" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" ) @@ -19,14 +20,12 @@ func (err InvalidCredentialsError) Error() string { } func CheckAuthenticationFailed(err error) bool { - prob := &upcloud.Problem{} - - if errors.As(err, &prob) { - errCode := prob.ErrorCode() - if errCode == upcloud.ErrCodeAuthenticationFailed || errCode == "INVALID_CREDENTIALS" { - return true - } + var errCode string + if prob := (*apierror.Problem)(nil); errors.As(err, &prob) { + errCode = prob.ErrorCode() + } else if prob := (*upcloud.Problem)(nil); errors.As(err, &prob) { + errCode = prob.ErrorCode() } - return false + return errCode == upcloud.ErrCodeAuthenticationFailed || errCode == "INVALID_CREDENTIALS" } diff --git a/internal/clierrors/invalid_credentials_test.go b/internal/clierrors/invalid_credentials_test.go new file mode 100644 index 000000000..26d4af4e7 --- /dev/null +++ b/internal/clierrors/invalid_credentials_test.go @@ -0,0 +1,30 @@ +package clierrors + +import ( + "fmt" + "testing" + + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" + "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" + "github.com/stretchr/testify/assert" +) + +func TestCheckAuthenticationFailed(t *testing.T) { + for _, test := range []struct { + name string + err error + expected bool + }{ + {name: "v8 authentication failed", err: &upcloud.Problem{Type: "https://developers.upcloud.com/1.3/errors#ERROR_AUTHENTICATION_FAILED"}, expected: true}, + {name: "v8 invalid credentials", err: &upcloud.Problem{Type: "INVALID_CREDENTIALS"}, expected: true}, + {name: "v9 authentication failed", err: &apierror.Problem{Type: "https://developers.upcloud.com/1.3/errors#ERROR_AUTHENTICATION_FAILED"}, expected: true}, + {name: "wrapped v9 invalid credentials", err: fmt.Errorf("resolving: %w", &apierror.Problem{Type: "INVALID_CREDENTIALS"}), expected: true}, + {name: "v8 other error", err: &upcloud.Problem{Type: "SERVICE_NOT_FOUND"}}, + {name: "v9 other error", err: &apierror.Problem{Type: "SERVICE_NOT_FOUND"}}, + {name: "plain error", err: fmt.Errorf("authentication failed")}, + } { + t.Run(test.name, func(t *testing.T) { + assert.Equal(t, test.expected, CheckAuthenticationFailed(test.err)) + }) + } +} diff --git a/internal/commands/database/create.go b/internal/commands/database/create.go index 3ff5efe25..ec8d37872 100644 --- a/internal/commands/database/create.go +++ b/internal/commands/database/create.go @@ -2,10 +2,12 @@ package database import ( "encoding/json" + "errors" "fmt" "slices" "strings" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" "github.com/UpCloudLtd/upcloud-cli/v3/internal/completion" "github.com/UpCloudLtd/upcloud-cli/v3/internal/config" @@ -13,12 +15,21 @@ import ( "github.com/UpCloudLtd/upcloud-cli/v3/internal/namedargs" "github.com/UpCloudLtd/upcloud-cli/v3/internal/output" "github.com/UpCloudLtd/upcloud-cli/v3/internal/ui" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/request" + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" + "github.com/google/uuid" "github.com/spf13/cobra" "github.com/spf13/pflag" ) +const ( + defaultPlanCompute = "rdb.standard.2CPU-8GB" + defaultPlanNodeCount = 2 + defaultPlanStorageGiB = 100 + defaultPlanBackups = "regular" +) + +var planComponentFlags = []string{"plan-compute", "plan-node-count", "plan-storage-gib", "plan-backups"} + type createCommand struct { *commands.BaseCommand params createParams @@ -39,86 +50,179 @@ func CreateCommand() commands.Command { --zone fi-hel1 \ --type pg \ --hostname-prefix mydb \ - --termination-protection \ + --plan-compute rdb.standard.2CPU-8GB \ + --plan-node-count 2 \ + --plan-storage-gib 120 \ + --plan-backups regular`, + `upctl database create \ + --title mydb \ + --zone fi-hel1 \ + --type pg \ + --hostname-prefix mydb \ + --plan 2x2xCPU-4GB-100GB \ + --enable-termination-protection \ --label env=dev \ --property max_connections=200`, ), } } -var defaultCreateParams = createParams{ - CreateManagedDatabaseRequest: request.CreateManagedDatabaseRequest{ - Plan: "2x2xCPU-4GB-100GB", - Type: upcloud.ManagedDatabaseServiceTypeMySQL, - }, -} - type createParams struct { - request.CreateManagedDatabaseRequest + title string + zone string + hostnamePrefix string + dbType string + plan string + planCompute string + planNodeCount int + planStorageGiB int + planBackups string + maintenanceDow string + maintenanceTime string labels []string networks []string - terminationProtection config.OptionalBoolean - dbType string properties []string + terminationProtection config.OptionalBoolean } -func (s *createParams) processParams(t *upcloud.ManagedDatabaseType) error { - if len(s.labels) > 0 { - labelSlice, err := labels.StringsToSliceOfLabels(s.labels) - if err != nil { - return err +func supportsPlanComponents(dbType string) bool { + return dbType == string(upcloudv9.DatabaseServiceTypePg) || dbType == string(upcloudv9.DatabaseServiceTypeMysql) +} + +func (p *createParams) request(properties map[string]propertySchema) (upcloudv9.DatabaseServiceCreateOpenAPI, error) { + req := upcloudv9.DatabaseServiceCreateOpenAPI{ + HostnamePrefix: p.hostnamePrefix, + Title: p.title, + Type: upcloudv9.DatabaseServiceType(p.dbType), + Zone: p.zone, + } + + if p.maintenanceDow != "" || p.maintenanceTime != "" { + req.Maintenance = &struct { + Dow upcloudv9.DatabaseMaintenanceDow `json:"dow"` + Time upcloudv9.DatabaseMaintenanceTime `json:"time"` + }{ + Dow: upcloudv9.DatabaseMaintenanceDow(p.maintenanceDow), + Time: p.maintenanceTime, } - s.Labels = labelSlice } - if s.dbType != "" { - s.Type = upcloud.ManagedDatabaseServiceType(s.dbType) + if len(p.labels) > 0 { + v9Labels, err := labels.StringsToLabels(p.labels, func(key, value string) upcloudv9.DatabaseLabelCreate { + return upcloudv9.DatabaseLabelCreate{Key: key, Value: value} + }) + if err != nil { + return req, err + } + req.Labels = &v9Labels } - if len(s.properties) > 0 { - props, err := processProperties(s.properties, t) + if len(p.properties) > 0 { + props, err := processProperties(p.properties, properties) + if err != nil { + return req, fmt.Errorf("invalid properties: %w", err) + } + // Properties are a generated union of per-engine types; setting the raw JSON keeps untyped key=value input. + raw, err := json.Marshal(props) if err != nil { - return fmt.Errorf("invalid properties: %w", err) + return req, fmt.Errorf("invalid properties: %w", err) } - s.Properties = props + var v9Props upcloudv9.DatabaseServiceCreateOpenAPI_Properties + if err := v9Props.UnmarshalJSON(raw); err != nil { + return req, fmt.Errorf("invalid properties: %w", err) + } + req.Properties = &v9Props } - if len(s.networks) > 0 { - networks, err := processNetworks(s.networks) + if len(p.networks) > 0 { + networks, err := processNetworks(p.networks) if err != nil { - return fmt.Errorf("invalid networks: %w", err) + return req, fmt.Errorf("invalid networks: %w", err) } - s.Networks = networks + req.Networks = &networks } - if s.terminationProtection.IsSet() { - terminationProtection := s.terminationProtection.Value() - s.TerminationProtection = &terminationProtection + if p.terminationProtection.IsSet() { + terminationProtection := p.terminationProtection.Value() + req.TerminationProtection = &terminationProtection } - return nil + return req, nil } -func isStringProperty(key upcloud.ManagedDatabasePropertyKey, t *upcloud.ManagedDatabaseType) bool { - if propType, ok := t.Properties[string(key)].Type.(string); ok { - return propType == "string" - } +// applyPlanComponents validates the plan components against the plan catalog and sets them on the request. +func (p *createParams) applyPlanComponents(catalog *upcloudv9.DatabasePlansResponse, changed func(string) bool, req *upcloudv9.DatabaseServiceCreateOpenAPI) error { + hint := fmt.Sprintf("run \"upctl database plans %s\" to list valid values", p.dbType) + for _, serviceType := range catalog.ServiceTypes { + if string(serviceType.Type) != p.dbType { + continue + } + for _, shape := range serviceType.ComputeShapes { + if shape.Compute != p.planCompute { + continue + } - if propType, ok := t.Properties[string(key)].Type.([]string); ok { - return slices.Contains(propType, "string") - } + nodeCounts := make([]string, 0, len(shape.NodeCounts)) + for _, n := range shape.NodeCounts { + nodeCounts = append(nodeCounts, fmt.Sprint(n)) + } + if !slices.Contains(nodeCounts, fmt.Sprint(p.planNodeCount)) { + return fmt.Errorf("--plan-node-count %d is not available for compute shape %s, valid node counts are %s", p.planNodeCount, shape.Compute, strings.Join(nodeCounts, ", ")) + } + req.PlanCompute = &p.planCompute + req.PlanNodeCount = &p.planNodeCount + + if shape.Storage == nil { + if changed("plan-storage-gib") { + return fmt.Errorf("compute shape %s does not support --plan-storage-gib", shape.Compute) + } + } else { + step := int(shape.Storage.StepGib) + valid := false + ranges := make([]string, 0, len(shape.Storage.Options)) + for _, option := range shape.Storage.Options { + base, maxGiB := int(option.BaseGib), int(option.MaxGib) + ranges = append(ranges, fmt.Sprintf("%d-%d", base, maxGiB)) + if p.planStorageGiB == base || (step > 0 && p.planStorageGiB > base && p.planStorageGiB <= maxGiB && (p.planStorageGiB-base)%step == 0) { + valid = true + } + } + if !valid { + return fmt.Errorf("--plan-storage-gib %d is not available for compute shape %s, valid totals per node are %s GiB in steps of %d GiB", p.planStorageGiB, shape.Compute, strings.Join(ranges, ", "), step) + } + req.PlanStorageGib = &p.planStorageGiB + } - return false + if shape.Backups == nil { + if changed("plan-backups") { + return fmt.Errorf("compute shape %s does not support --plan-backups", shape.Compute) + } + } else { + tiers := make([]string, 0, len(*shape.Backups)) + for _, tier := range *shape.Backups { + tiers = append(tiers, string(tier)) + } + if !slices.Contains(tiers, p.planBackups) { + return fmt.Errorf("--plan-backups %q is not available for compute shape %s, valid backup tiers are %s", p.planBackups, shape.Compute, strings.Join(tiers, ", ")) + } + backups := upcloudv9.DatabaseServiceCreateOpenAPIPlanBackups(p.planBackups) + req.PlanBackups = &backups + } + return nil + } + return fmt.Errorf("--plan-compute %q is not available for %s, %s", p.planCompute, p.dbType, hint) + } + return fmt.Errorf("database type %s has no component plans, use --plan", p.dbType) } -func processProperties(in []string, t *upcloud.ManagedDatabaseType) (request.ManagedDatabasePropertiesRequest, error) { - resp := request.ManagedDatabasePropertiesRequest{} +func processProperties(in []string, schemas map[string]propertySchema) (map[string]any, error) { + resp := map[string]any{} for _, prop := range in { parts := strings.SplitN(prop, "=", 2) if len(parts) != 2 { return resp, fmt.Errorf("invalid property format: %s, expected key=value", prop) } - key := upcloud.ManagedDatabasePropertyKey(parts[0]) + key := parts[0] value := parts[1] // Remove quotes from the start and end of the value if they exist @@ -128,25 +232,25 @@ func processProperties(in []string, t *upcloud.ManagedDatabaseType) (request.Man } // Handle numerical string values, e.g. Postgres version - if isStringProperty(key, t) { - resp.Set(key, value) + if schemas[key].allowsString() { + resp[key] = value continue } var parsedValue any if err := json.Unmarshal([]byte(value), &parsedValue); err != nil { - resp.Set(key, value) // Set as plain string if parsing fails + resp[key] = value // Set as plain string if parsing fails } else { - resp.Set(key, parsedValue) + resp[key] = parsedValue } } return resp, nil } -func processNetworks(in []string) ([]upcloud.ManagedDatabaseNetwork, error) { - var networks []upcloud.ManagedDatabaseNetwork +func processNetworks(in []string) ([]upcloudv9.DatabaseNetworkCreate, error) { + var networks []upcloudv9.DatabaseNetworkCreate for _, netStr := range in { - network := upcloud.ManagedDatabaseNetwork{} + network := upcloudv9.DatabaseNetworkCreate{} pairs := strings.SplitSeq(netStr, ",") for pair := range pairs { @@ -160,13 +264,17 @@ func processNetworks(in []string) ([]upcloud.ManagedDatabaseNetwork, error) { switch key { case "family": - network.Family = value + network.Family = upcloudv9.DatabaseNetworkFamily(value) case "name": network.Name = value case "type": - network.Type = value + network.Type = upcloudv9.DatabaseNetworkType(value) case "uuid": - network.UUID = &value + id, err := uuid.Parse(value) + if err != nil { + return nil, fmt.Errorf("invalid network uuid %q: %w", value, err) + } + network.Uuid = &id default: return nil, fmt.Errorf("unknown network parameter: %s", key) } @@ -178,19 +286,28 @@ func processNetworks(in []string) ([]upcloud.ManagedDatabaseNetwork, error) { // InitCommand implements commands.InitializeCommand func (s *createCommand) InitCommand() { + s.Cobra().Long = commands.WrapLongDescription(`Create a new database + +For pg and mysql, select the plan by its components with --plan-compute, --plan-node-count, --plan-storage-gib, and --plan-backups. When any of these flags is given, the omitted ones use their defaults. Run "upctl database plans " to list the valid compute shapes, node counts, storage ranges, and backup tiers. --plan-storage-gib is the total storage per node, not additional storage. + +--plan is deprecated for pg and mysql, but still supported, and it is required for other database types. Run "upctl database plans --show-legacy" to list plan names. --plan cannot be combined with the --plan-* flags. Without any plan flag, pg and mysql use the default of every --plan-* flag.`) + flags := &pflag.FlagSet{} - s.params = createParams{CreateManagedDatabaseRequest: request.CreateManagedDatabaseRequest{}} - def := defaultCreateParams - flags.StringVar(&s.params.HostNamePrefix, "hostname-prefix", def.HostNamePrefix, "A host name prefix for the database") - flags.StringVar(&s.params.Title, "title", def.Title, "A short, informational description.") - flags.StringVar(&s.params.Plan, "plan", def.Plan, "Plan to use for the database. Run `upctl database plans [database type]` to list all available plans.") - flags.StringVar(&s.params.Zone, "zone", def.Zone, namedargs.ZoneDescription("database")) - flags.StringVar(&s.params.dbType, "type", string(def.Type), "Type of the database") - flags.StringVar(&s.params.Maintenance.DayOfWeek, "maintenance-dow", def.Maintenance.DayOfWeek, "Full name of weekday in English, lower case(sunday) for automatic maintenance day of the week. Set randomly if not provided.") - flags.StringVar(&s.params.Maintenance.Time, "maintenance-time", def.Maintenance.Time, "Database time in UTC of automatic maintenance HH:MM:SS. Set randomly if not provided.") - flags.StringSliceVar(&s.params.labels, "label", def.labels, "Labels to describe the database in `key=value` format, multiple can be declared.\nUsage: --label env=dev\n\n--label owner=operations") - flags.StringArrayVar(&s.params.networks, "network", def.networks, "A network interface for the database, multiple can be declared.\nUsage: --network name=network-name,family=IPv4,type=private,uuid=030e83d2-d413-4d19-b1c9-af05cdb60c1f") - config.AddEnableOrDisableFlag(flags, &s.params.terminationProtection, def.terminationProtection.Value(), "termination-protection", "termination protection to prevent the database instance from being powered off or deleted") + s.params = createParams{} + flags.StringVar(&s.params.hostnamePrefix, "hostname-prefix", "", "A host name prefix for the database") + flags.StringVar(&s.params.title, "title", "", "A short, informational description.") + flags.StringVar(&s.params.plan, "plan", "", "Deprecated for pg and mysql, use the --plan-* flags instead. Plan name, required for database types other than pg and mysql.") + flags.StringVar(&s.params.planCompute, "plan-compute", defaultPlanCompute, "Compute shape for pg and mysql, see the Compute shape column of \"upctl database plans \".") + flags.IntVar(&s.params.planNodeCount, "plan-node-count", defaultPlanNodeCount, "Number of nodes for pg and mysql.") + flags.IntVar(&s.params.planStorageGiB, "plan-storage-gib", defaultPlanStorageGiB, "Total storage per node in GiB for pg and mysql.") + flags.StringVar(&s.params.planBackups, "plan-backups", defaultPlanBackups, "Backup tier for pg and mysql.") + flags.StringVar(&s.params.zone, "zone", "", namedargs.ZoneDescription("database")) + flags.StringVar(&s.params.dbType, "type", string(upcloudv9.DatabaseServiceTypeMysql), "Type of the database") + flags.StringVar(&s.params.maintenanceDow, "maintenance-dow", "", "Full name of weekday in English, lower case(sunday) for automatic maintenance day of the week. Set randomly if not provided. Requires --maintenance-time.") + flags.StringVar(&s.params.maintenanceTime, "maintenance-time", "", "Database time in UTC of automatic maintenance HH:MM:SS. Set randomly if not provided. Requires --maintenance-dow.") + flags.StringSliceVar(&s.params.labels, "label", nil, "Labels to describe the database in `key=value` format, multiple can be declared.\nUsage: --label env=dev\n\n--label owner=operations") + flags.StringArrayVar(&s.params.networks, "network", nil, "A network interface for the database, multiple can be declared.\nUsage: --network name=network-name,family=IPv4,type=private,uuid=030e83d2-d413-4d19-b1c9-af05cdb60c1f") + config.AddEnableOrDisableFlag(flags, &s.params.terminationProtection, false, "termination-protection", "termination protection to prevent the database instance from being powered off or deleted") flags.StringArrayVar(&s.params.properties, "property", nil, "Properties for the database in `key=value` format. Can be specified multiple times.") config.AddToggleFlag(flags, &s.wait, "wait", false, "Wait for database to be in running state before returning.") @@ -200,7 +317,11 @@ func (s *createCommand) InitCommand() { commands.Must(s.Cobra().MarkFlagRequired("title")) commands.Must(s.Cobra().MarkFlagRequired("zone")) commands.Must(s.Cobra().MarkFlagRequired("hostname-prefix")) - for _, flag := range []string{"hostname-prefix", "title", "plan", "maintenance-dow", "maintenance-time", "label", "network", "property"} { + for _, flag := range planComponentFlags { + s.Cobra().MarkFlagsMutuallyExclusive("plan", flag) + } + s.Cobra().MarkFlagsRequiredTogether("maintenance-dow", "maintenance-time") + for _, flag := range append([]string{"hostname-prefix", "title", "plan", "maintenance-dow", "maintenance-time", "label", "network", "property"}, planComponentFlags...) { commands.Must(s.Cobra().RegisterFlagCompletionFunc(flag, cobra.NoFileCompletions)) } } @@ -210,36 +331,86 @@ func (s *createCommand) InitCommandWithConfig(cfg *config.Config) { commands.Must(s.Cobra().RegisterFlagCompletionFunc("zone", namedargs.CompletionFunc(completion.Zone{}, cfg))) } +// usesPlanComponents reports whether the plan is selected by components, and rejects plan flags that cannot be used for the database type. +func (s *createCommand) usesPlanComponents() (bool, error) { + flags := s.Cobra().Flags() + componentFlags := slices.ContainsFunc(planComponentFlags, flags.Changed) + switch { + case componentFlags && !supportsPlanComponents(s.params.dbType): + return false, fmt.Errorf("the --plan-* flags are only supported for pg and mysql, use --plan for database type %q", s.params.dbType) + case componentFlags && s.params.planNodeCount < 1: + return false, fmt.Errorf("--plan-node-count must be a positive integer, got %d", s.params.planNodeCount) + case componentFlags && s.params.planStorageGiB < 1: + return false, fmt.Errorf("--plan-storage-gib must be a positive integer, got %d", s.params.planStorageGiB) + case flags.Changed("plan"): + return false, nil + case supportsPlanComponents(s.params.dbType): + return true, nil + default: + return false, fmt.Errorf("--plan is required for database type %q, run \"upctl database plans %s --show-legacy\" to list available plans", s.params.dbType, s.params.dbType) + } +} + // ExecuteWithoutArguments implements commands.NoArgumentCommand func (s *createCommand) ExecuteWithoutArguments(exec commands.Executor) (output.Output, error) { - svc := exec.All() - msg := fmt.Sprintf("Creating database %v", s.params.Title) + useComponents, err := s.usesPlanComponents() + if err != nil { + return nil, err + } + + client, err := v9Client(exec) + if err != nil { + return nil, err + } + + msg := fmt.Sprintf("Creating database %v", s.params.title) exec.PushProgressStarted(msg) - t, err := svc.GetManagedDatabaseServiceType(exec.Context(), &request.GetManagedDatabaseServiceTypeRequest{ - Type: s.params.dbType, - }) + properties, err := getServiceTypeProperties(exec.Context(), client, s.params.dbType) if err != nil { return commands.HandleError(exec, msg, err) } - if err := s.params.processParams(t); err != nil { + req, err := s.params.request(properties) + if err != nil { return nil, err } - req := s.params.CreateManagedDatabaseRequest - res, err := svc.CreateManagedDatabase(exec.Context(), &req) + if useComponents { + plans, err := client.ListDatabasePlansWithResponse(exec.Context()) + if err != nil { + return commands.HandleError(exec, msg, err) + } + if plans.JSON200 == nil { + return commands.HandleError(exec, msg, apierror.FromResponse(plans.StatusCode(), plans.Body)) + } + if err := s.params.applyPlanComponents(plans.JSON200, s.Cobra().Flags().Changed, &req); err != nil { + return commands.HandleError(exec, msg, err) + } + } else { + req.Plan = &s.params.plan + } + + res, err := client.CreateDatabaseWithResponse(exec.Context(), req) if err != nil { return commands.HandleError(exec, msg, err) } + if res.JSON201 == nil { + return commands.HandleError(exec, msg, apierror.FromResponse(res.StatusCode(), res.Body)) + } + db := res.JSON201 + if db.Uuid == nil { + return commands.HandleError(exec, msg, errors.New("the API response did not include the database UUID")) + } + id := db.Uuid.String() if s.wait.Value() { - WaitForManagedDatabaseState(res.UUID, upcloud.ManagedDatabaseStateRunning, exec, msg) + WaitForManagedDatabaseState(id, databaseStateRunning, exec, msg) } else { exec.PushProgressSuccess(msg) } - return output.MarshaledWithHumanDetails{Value: res, Details: []output.DetailRow{ - {Title: "UUID", Value: res.UUID, Colour: ui.DefaultUUUIDColours}, + return output.MarshaledWithHumanDetails{Value: db, Details: []output.DetailRow{ + {Title: "UUID", Value: id, Colour: ui.DefaultUUUIDColours}, }}, nil } diff --git a/internal/commands/database/create_test.go b/internal/commands/database/create_test.go index 22660a2d6..736fab923 100644 --- a/internal/commands/database/create_test.go +++ b/internal/commands/database/create_test.go @@ -1,201 +1,307 @@ package database import ( + "encoding/json" + "net/http" "testing" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" - "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands/storage" "github.com/UpCloudLtd/upcloud-cli/v3/internal/config" smock "github.com/UpCloudLtd/upcloud-cli/v3/internal/mock" "github.com/UpCloudLtd/upcloud-cli/v3/internal/mockexecute" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/request" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" ) -func TestCreateCommand(t *testing.T) { - databaseDetailsMaint := upcloud.ManagedDatabase{ - UUID: "0927dfd6-3884-4079-a948-3a8881df1a7a", +const createdDatabaseUUID = "0927dfd6-3884-4079-a948-3a8881df1a7a" + +const planCatalog = `{"service_types": [ + {"type": "pg", "componentised": true, "node_counts": [1, 2, 3], "zones": ["fi-hel1"], "compute_shapes": [ + {"compute": "rdb.standard.2CPU-8GB", "family": "standard", "cpu": 2, "memory_gb": 8, "dynamic_storage_supported": true, + "node_counts": [1, 2, 3], "backups": ["regular", "extended"], + "storage": {"dynamic_max_multiplier": 4, "step_gib": 10, "total_cap_gib": 10240, "options": [{"base_gib": 10, "max_gib": 50}, {"base_gib": 80, "max_gib": 400}]}}, + {"compute": "rdb.development.1CPU-1GB", "family": "development", "cpu": 1, "memory_gb": 1, "dynamic_storage_supported": true, + "node_counts": [1], "backups": ["mini"], + "storage": {"dynamic_max_multiplier": 4, "step_gib": 10, "total_cap_gib": null, "options": [{"base_gib": 10, "max_gib": 50}]}} + ]}, + {"type": "mysql", "componentised": true, "node_counts": [1, 2, 3], "zones": ["fi-hel1"], "compute_shapes": [ + {"compute": "rdb.standard.2CPU-8GB", "family": "standard", "cpu": 2, "memory_gb": 8, "dynamic_storage_supported": true, + "node_counts": [1, 2, 3], "backups": ["regular", "extended"], + "storage": {"dynamic_max_multiplier": 4, "step_gib": 10, "total_cap_gib": 10240, "options": [{"base_gib": 80, "max_gib": 400}]}} + ]} +]}` + +const createdDatabase = `{"uuid": "` + createdDatabaseUUID + `", "title": "db-test", "type": "pg", "state": "rebuilding", "plan": "rdb.standard.2x-2CPU-8GB-100GB-regular"}` + +// serviceType uses a list type for version, as the live API does. +const serviceType = `{"name": "pg", "properties": { + "version": {"type": ["string", "null"], "title": "Version"}, + "numeric_string": {"type": "string", "title": "Numeric string"}, + "max_connections": {"type": "integer", "title": "Max connections"} +}}` + +func newCreateAPI(t *testing.T, create fakeResponse) *fakeAPI { + responses := map[string]fakeResponse{ + "GET /1.3/database/plans": {status: http.StatusOK, body: planCatalog}, + "POST /1.3/database": create, + "GET /1.3/database/" + createdDatabaseUUID: {sequence: []fakeResponse{ + {status: http.StatusOK, body: `{"uuid": "` + createdDatabaseUUID + `", "state": "rebuilding"}`}, + {status: http.StatusOK, body: `{"uuid": "` + createdDatabaseUUID + `", "state": "running"}`}, + }}, } - serviceType := upcloud.ManagedDatabaseType{ - Properties: map[string]upcloud.ManagedDatabaseServiceProperty{ - "version": { - Type: []string{"string", "null"}, - }, - "numeric_string": { - Type: "string", - }, - }, + for _, dbType := range []string{"mysql", "pg", "opensearch", "valkey"} { + responses["GET /1.3/database/service-types/"+dbType] = fakeResponse{status: http.StatusOK, body: serviceType} } + return newFakeAPI(t, responses) +} + +func runCreate(t *testing.T, api *fakeAPI, conf *config.Config, args ...string) (string, error) { + t.Helper() + c := commands.BuildCommand(CreateCommand(), nil, conf) + c.Cobra().SetArgs(args) + return mockexecute.MockExecuteWithV9(c, &smock.Service{}, api.client, conf) +} +var requiredCreateArgs = []string{"--title", "db-test", "--zone", "fi-hel1", "--hostname-prefix", "testdb"} + +func TestCreateCommand_Request(t *testing.T) { for _, test := range []struct { - name string - args []string - createDatabaseReq request.CreateManagedDatabaseRequest - error string + name string + args []string + expected string + components bool }{ { - name: "minimum required parameters", - args: []string{ - "--title", "db-test", - "--zone", "fi-hel1", - "--hostname-prefix", "testdb", - }, - createDatabaseReq: request.CreateManagedDatabaseRequest{ - Title: "db-test", - Zone: "fi-hel1", - HostNamePrefix: "testdb", - Plan: "2x2xCPU-4GB-100GB", - Type: upcloud.ManagedDatabaseServiceTypeMySQL, - }, + name: "no plan flag uses the component defaults", + expected: `{"hostname_prefix": "testdb", "title": "db-test", "type": "mysql", "zone": "fi-hel1", + "plan_compute": "rdb.standard.2CPU-8GB", "plan_node_count": 2, "plan_storage_gib": 100, "plan_backups": "regular"}`, + components: true, }, { - name: "pg with label, protection, and version parameters", - args: []string{ - "--title", "full-test", - "--zone", "fi-hel1", - "--hostname-prefix", "fulldb", - "--plan", "4x4xCPU-8GB-200GB", - "--type", "pg", - "--label", "env=test,app=database", - "--enable-termination-protection", - "--property", "version=13", - }, - createDatabaseReq: request.CreateManagedDatabaseRequest{ - Title: "full-test", - Zone: "fi-hel1", - HostNamePrefix: "fulldb", - Plan: "4x4xCPU-8GB-200GB", - Type: upcloud.ManagedDatabaseServiceTypePostgreSQL, - Labels: []upcloud.Label{{Key: "env", Value: "test"}, {Key: "app", Value: "database"}}, - TerminationProtection: boolPtr(true), - Properties: request.ManagedDatabasePropertiesRequest{ - "version": "13", - }, - }, + name: "explicit legacy plan with labels, termination protection and string property", + args: []string{"--type", "pg", "--plan", "4x4xCPU-8GB-200GB", "--label", "env=test,app=database", "--enable-termination-protection", "--property", "version=13", "--property", "max_connections=200"}, + expected: `{"hostname_prefix": "testdb", "plan": "4x4xCPU-8GB-200GB", "title": "db-test", "type": "pg", "zone": "fi-hel1", + "labels": [{"key": "env", "value": "test"}, {"key": "app", "value": "database"}], + "termination_protection": true, "properties": {"version": "13", "max_connections": 200}}`, }, { - name: "opensearch with properties parameters", + name: "opensearch with typed properties", args: []string{ - "--title", "full-test", - "--zone", "fi-hel1", - "--hostname-prefix", "fulldb", - "--plan", "4x4xCPU-8GB-200GB", - "--type", "opensearch", - "--property", "saml={\"enabled\":true}", // without quotes - "--property", "openid=\"{\"client_id\":\"test_client_id\"}\"", // with quotes + "--type", "opensearch", "--plan", "1x2xCPU-4GB-80GB-1D", + "--property", `saml={"enabled":true}`, + "--property", `openid="{"client_id":"test_client_id"}"`, "--property", "ism_enabled=true", "--property", "custom_domain=custom.upcloud.com", "--property", "numeric_string=123", }, - createDatabaseReq: request.CreateManagedDatabaseRequest{ - Title: "full-test", - Zone: "fi-hel1", - HostNamePrefix: "fulldb", - Plan: "4x4xCPU-8GB-200GB", - Type: upcloud.ManagedDatabaseServiceTypeOpenSearch, - Properties: request.ManagedDatabasePropertiesRequest{ - "ism_enabled": true, - "custom_domain": "custom.upcloud.com", - "saml": map[string]any{"enabled": true}, - "openid": map[string]any{"client_id": "test_client_id"}, - "numeric_string": "123", - }, - }, + expected: `{"hostname_prefix": "testdb", "plan": "1x2xCPU-4GB-80GB-1D", "title": "db-test", "type": "opensearch", "zone": "fi-hel1", + "properties": {"saml": {"enabled": true}, "openid": {"client_id": "test_client_id"}, "ism_enabled": true, "custom_domain": "custom.upcloud.com", "numeric_string": "123"}}`, }, { - name: "mysql default database type", + name: "maintenance and networks", args: []string{ - "--title", "mysql-test", - "--zone", "fi-hel1", - "--hostname-prefix", "mysqldb", - }, - createDatabaseReq: request.CreateManagedDatabaseRequest{ - Title: "mysql-test", - Zone: "fi-hel1", - HostNamePrefix: "mysqldb", - Plan: "2x2xCPU-4GB-100GB", - Type: upcloud.ManagedDatabaseServiceTypeMySQL, + "--maintenance-dow", "monday", "--maintenance-time", "02:00:00", + "--network", "name=net-1,family=IPv4,type=private,uuid=030e83d2-d413-4d19-b1c9-af05cdb60c1f", }, + expected: `{"hostname_prefix": "testdb", "title": "db-test", "type": "mysql", "zone": "fi-hel1", + "plan_compute": "rdb.standard.2CPU-8GB", "plan_node_count": 2, "plan_storage_gib": 100, "plan_backups": "regular", + "maintenance": {"dow": "monday", "time": "02:00:00"}, + "networks": [{"family": "IPv4", "name": "net-1", "type": "private", "uuid": "030e83d2-d413-4d19-b1c9-af05cdb60c1f"}]}`, + components: true, }, { - name: "maintenance-dow and maintenance-time", - args: []string{ - "--title", "mysql-test", - "--zone", "fi-hel1", - "--hostname-prefix", "mysqldb", - "--maintenance-dow", "monday", - "--maintenance-time", "02:00", - }, - createDatabaseReq: request.CreateManagedDatabaseRequest{ - Title: "mysql-test", - Zone: "fi-hel1", - HostNamePrefix: "mysqldb", - Plan: "2x2xCPU-4GB-100GB", - Type: upcloud.ManagedDatabaseServiceTypeMySQL, - Maintenance: request.ManagedDatabaseMaintenanceTimeRequest{ - DayOfWeek: "monday", - Time: "02:00", - }, - }, + name: "component selection uses defaults for omitted components", + args: []string{"--type", "pg", "--plan-storage-gib", "120"}, + expected: `{"hostname_prefix": "testdb", "title": "db-test", "type": "pg", "zone": "fi-hel1", + "plan_compute": "rdb.standard.2CPU-8GB", "plan_node_count": 2, "plan_storage_gib": 120, "plan_backups": "regular"}`, + components: true, }, { - name: "missing required title parameter", - args: []string{ - "--zone", "fi-hel1", - "--hostname-prefix", "testdb", - }, - error: "required flag(s) \"title\" not set", + name: "component selection with every component", + args: []string{"--type", "mysql", "--plan-compute", "rdb.standard.2CPU-8GB", "--plan-node-count", "3", "--plan-storage-gib", "400", "--plan-backups", "extended"}, + expected: `{"hostname_prefix": "testdb", "title": "db-test", "type": "mysql", "zone": "fi-hel1", + "plan_compute": "rdb.standard.2CPU-8GB", "plan_node_count": 3, "plan_storage_gib": 400, "plan_backups": "extended"}`, + components: true, }, { - name: "missing required zone parameter", - args: []string{ - "--title", "db-test", - "--hostname-prefix", "testdb", - }, - error: "required flag(s) \"zone\" not set", + name: "component selection on the base storage of a shape", + args: []string{"--type", "pg", "--plan-compute", "rdb.development.1CPU-1GB", "--plan-node-count", "1", "--plan-storage-gib", "10", "--plan-backups", "mini"}, + expected: `{"hostname_prefix": "testdb", "title": "db-test", "type": "pg", "zone": "fi-hel1", + "plan_compute": "rdb.development.1CPU-1GB", "plan_node_count": 1, "plan_storage_gib": 10, "plan_backups": "mini"}`, + components: true, }, + } { + t.Run(test.name, func(t *testing.T) { + api := newCreateAPI(t, fakeResponse{status: http.StatusCreated, body: createdDatabase}) + + _, err := runCreate(t, api, config.New(), append(requiredCreateArgs, test.args...)...) + require.NoError(t, err) + + creates := api.requestsTo(http.MethodPost, "/1.3/database") + require.Len(t, creates, 1) + assert.JSONEq(t, test.expected, string(creates[0].Body)) + + if test.components { + var body map[string]any + require.NoError(t, json.Unmarshal(creates[0].Body, &body)) + assert.NotContains(t, body, "plan", "component selection must not send an implicit plan") + assert.NotContains(t, body, "additional_disk_space_gib", "plan_storage_gib is exclusive with additional_disk_space_gib") + } + }) + } +} + +func TestCreateCommand_Errors(t *testing.T) { + for _, test := range []struct { + name string + args []string + error string + // beforeAPI marks errors that must be reported without any API request. + beforeAPI bool + }{ { - name: "missing required hostname-prefix parameter", - args: []string{ - "--title", "db-test", - "--zone", "fi-hel1", - }, - error: "required flag(s) \"hostname-prefix\" not set", + name: "plan and a component flag are mutually exclusive", + args: append(requiredCreateArgs, "--type", "pg", "--plan", "2x2xCPU-4GB-100GB", "--plan-compute", "rdb.standard.2CPU-8GB"), + error: "if any flags in the group [plan plan-compute] are set none of the others can be; [plan plan-compute] were all set", + beforeAPI: true, + }, + { + name: "invalid numeric value", + args: append(requiredCreateArgs, "--type", "pg", "--plan-node-count", "two"), + error: `invalid argument "two" for "--plan-node-count" flag`, + beforeAPI: true, + }, + { + name: "non-positive node count", + args: append(requiredCreateArgs, "--type", "pg", "--plan-node-count", "0"), + error: "--plan-node-count must be a positive integer, got 0", + beforeAPI: true, + }, + { + name: "negative storage", + args: append(requiredCreateArgs, "--type", "pg", "--plan-storage-gib", "-10"), + error: "--plan-storage-gib must be a positive integer, got -10", + beforeAPI: true, + }, + { + name: "component flags for an engine without component plans", + args: append(requiredCreateArgs, "--type", "opensearch", "--plan-compute", "rdb.standard.2CPU-8GB"), + error: `the --plan-* flags are only supported for pg and mysql, use --plan for database type "opensearch"`, + beforeAPI: true, + }, + { + name: "engine without component plans requires --plan", + args: append(requiredCreateArgs, "--type", "valkey"), + error: `--plan is required for database type "valkey", run "upctl database plans valkey --show-legacy" to list available plans`, + beforeAPI: true, + }, + { + name: "maintenance flags must be used together", + args: append(requiredCreateArgs, "--maintenance-dow", "monday"), + error: "if any flags in the group [maintenance-dow maintenance-time] are set they must all be set; missing [maintenance-time]", + beforeAPI: true, + }, + { + name: "invalid network uuid", + args: append(requiredCreateArgs, "--network", "name=net-1,family=IPv4,type=private,uuid=not-a-uuid"), + error: `invalid networks: invalid network uuid "not-a-uuid"`, + }, + { + name: "storage between the base options of a shape", + args: append(requiredCreateArgs, "--type", "pg", "--plan-storage-gib", "60"), + error: "--plan-storage-gib 60 is not available for compute shape rdb.standard.2CPU-8GB, valid totals per node are 10-50, 80-400 GiB in steps of 10 GiB", + }, + { + name: "storage not aligned to the storage step", + args: append(requiredCreateArgs, "--type", "pg", "--plan-storage-gib", "125"), + error: "--plan-storage-gib 125 is not available for compute shape rdb.standard.2CPU-8GB", + }, + { + name: "default node count not offered by the compute shape", + args: append(requiredCreateArgs, "--type", "pg", "--plan-compute", "rdb.development.1CPU-1GB"), + error: "--plan-node-count 2 is not available for compute shape rdb.development.1CPU-1GB, valid node counts are 1", + }, + { + name: "unknown compute shape", + args: append(requiredCreateArgs, "--type", "pg", "--plan-compute", "rdb.standard.99CPU-1GB"), + error: `--plan-compute "rdb.standard.99CPU-1GB" is not available for pg, run "upctl database plans pg" to list valid values`, + }, + { + name: "backup tier not offered by the compute shape", + args: append(requiredCreateArgs, "--type", "pg", "--plan-backups", "mini"), + error: `--plan-backups "mini" is not available for compute shape rdb.standard.2CPU-8GB, valid backup tiers are regular, extended`, + }, + { + name: "missing required title", + args: []string{"--zone", "fi-hel1", "--hostname-prefix", "testdb"}, + error: `required flag(s) "title" not set`, + beforeAPI: true, + }, + { + name: "missing required zone", + args: []string{"--title", "db-test", "--hostname-prefix", "testdb"}, + error: `required flag(s) "zone" not set`, + beforeAPI: true, + }, + { + name: "missing required hostname-prefix", + args: []string{"--title", "db-test", "--zone", "fi-hel1"}, + error: `required flag(s) "hostname-prefix" not set`, + beforeAPI: true, }, } { t.Run(test.name, func(t *testing.T) { - conf := config.New() - testCmd := CreateCommand() - mService := new(smock.Service) - - storage.CachedStorages = nil - createDatabaseReq := test.createDatabaseReq - mService.On("CreateManagedDatabase", &createDatabaseReq).Return(&databaseDetailsMaint, nil) - mService.On("GetManagedDatabaseServiceType", mock.Anything).Return(&serviceType, nil) - - c := commands.BuildCommand(testCmd, nil, conf) - - c.Cobra().SetArgs(test.args) - _, err := mockexecute.MockExecute(c, mService, conf) - - if test.error != "" { - if err == nil { - t.Errorf("expected error '%v', got nil", test.error) - } else { - assert.Equal(t, test.error, err.Error()) - } - } else { - assert.NoError(t, err) - // Fix: Check for CreateManagedDatabase method call instead of CreateDatabase - mService.AssertNumberOfCalls(t, "CreateManagedDatabase", 1) + api := newCreateAPI(t, fakeResponse{status: http.StatusCreated, body: createdDatabase}) + + _, err := runCreate(t, api, config.New(), test.args...) + require.Error(t, err) + assert.Contains(t, err.Error(), test.error) + assert.Empty(t, api.requestsTo(http.MethodPost, "/1.3/database"), "the database must not be created") + if test.beforeAPI { + assert.Empty(t, api.all(), "the error must be reported before calling the API") } }) } } -// Helper function to create a bool pointer -func boolPtr(b bool) *bool { - return &b +func TestCreateCommand_Output(t *testing.T) { + api := newCreateAPI(t, fakeResponse{status: http.StatusCreated, body: createdDatabase}) + out, err := runCreate(t, api, config.New(), requiredCreateArgs...) + require.NoError(t, err) + assert.Contains(t, out, createdDatabaseUUID) + + conf := config.New() + conf.Viper().Set(config.KeyOutput, config.ValueOutputJSON) + out, err = runCreate(t, api, conf, requiredCreateArgs...) + require.NoError(t, err) + var body map[string]any + require.NoError(t, json.Unmarshal([]byte(out), &body)) + assert.Equal(t, createdDatabaseUUID, body["uuid"]) + assert.Equal(t, "rdb.standard.2x-2CPU-8GB-100GB-regular", body["plan"]) +} + +func TestCreateCommand_Wait(t *testing.T) { + api := newCreateAPI(t, fakeResponse{status: http.StatusCreated, body: createdDatabase}) + + out, err := runCreate(t, api, config.New(), append(requiredCreateArgs, "--wait")...) + require.NoError(t, err) + assert.Contains(t, out, createdDatabaseUUID) + assert.Len(t, api.requestsTo(http.MethodGet, "/1.3/database/"+createdDatabaseUUID), 2, "polls until the database is running") +} + +func TestCreateCommand_APIError(t *testing.T) { + api := newCreateAPI(t, fakeResponse{ + status: http.StatusUnprocessableEntity, + contentType: "application/problem+json", + body: `{"type": "https://developers.upcloud.com/1.3/errors#ERROR_INVALID_PLAN", "title": "Plan is not available", "status": 422, "correlation_id": "abc"}`, + }) + + _, err := runCreate(t, api, config.New(), append(requiredCreateArgs, "--type", "pg", "--plan-storage-gib", "120")...) + require.Error(t, err) + assert.EqualError(t, err, "Plan is not available (type=https://developers.upcloud.com/1.3/errors#ERROR_INVALID_PLAN, status=422, correlation_id=abc)") + var problem *apierror.Problem + require.ErrorAs(t, err, &problem) + assert.Equal(t, "INVALID_PLAN", problem.ErrorCode()) + assert.False(t, apierror.IsNotFound(err)) } diff --git a/internal/commands/database/database.go b/internal/commands/database/database.go index 84790c5c0..41048bbec 100644 --- a/internal/commands/database/database.go +++ b/internal/commands/database/database.go @@ -7,8 +7,6 @@ import ( "github.com/UpCloudLtd/progress/messages" "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/request" ) // BaseDatabaseCommand creates the base "database" command @@ -28,16 +26,24 @@ func (db *databaseCommand) InitCommand() { } // waitForManagedDatabaseState waits for database to reach given state and updates progress message with key matching given msg. Finally, progress message is updated back to given msg and either done state or timeout warning. -func WaitForManagedDatabaseState(uuid string, state upcloud.ManagedDatabaseState, exec commands.Executor, msg string) { +func WaitForManagedDatabaseState(uuid string, state string, exec commands.Executor, msg string) { exec.PushProgressUpdateMessage(msg, fmt.Sprintf("Waiting for database %s to be in %s state", uuid, state)) ctx, cancel := context.WithTimeout(exec.Context(), 15*time.Minute) defer cancel() - if _, err := exec.All().WaitForManagedDatabaseState(ctx, &request.WaitForManagedDatabaseStateRequest{ - UUID: uuid, - DesiredState: state, - }); err != nil { + err := func() error { + client, err := v9Client(exec) + if err != nil { + return err + } + id, err := parseDatabaseUUID(uuid) + if err != nil { + return err + } + return waitForDatabaseState(ctx, client, id, state) + }() + if err != nil { exec.PushProgressUpdate(messages.Update{ Key: msg, Message: msg, diff --git a/internal/commands/database/delete.go b/internal/commands/database/delete.go index 9fda50aaf..71b15c959 100644 --- a/internal/commands/database/delete.go +++ b/internal/commands/database/delete.go @@ -4,13 +4,14 @@ import ( "fmt" "time" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" "github.com/UpCloudLtd/upcloud-cli/v3/internal/completion" "github.com/UpCloudLtd/upcloud-cli/v3/internal/config" "github.com/UpCloudLtd/upcloud-cli/v3/internal/output" "github.com/UpCloudLtd/upcloud-cli/v3/internal/resolver" - "github.com/UpCloudLtd/upcloud-cli/v3/internal/utils" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/request" + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" + "github.com/google/uuid" "github.com/spf13/pflag" ) @@ -43,30 +44,43 @@ func (c *deleteCommand) InitCommand() { c.AddFlags(flags) } -func Delete(exec commands.Executor, uuid string, disableTerminationProtection, wait bool) (output.Output, error) { - svc := exec.All() - msg := fmt.Sprintf("Deleting database %s", uuid) +func Delete(exec commands.Executor, uuidStr string, disableTerminationProtection, wait bool) (output.Output, error) { + msg := fmt.Sprintf("Deleting database %s", uuidStr) exec.PushProgressStarted(msg) + client, err := v9Client(exec) + if err != nil { + return commands.HandleError(exec, msg, err) + } + id, err := parseDatabaseUUID(uuidStr) + if err != nil { + return commands.HandleError(exec, msg, err) + } + if disableTerminationProtection { b := false - _, err := svc.ModifyManagedDatabase(exec.Context(), &request.ModifyManagedDatabaseRequest{ - UUID: uuid, + res, err := client.ModifyDatabaseWithResponse(exec.Context(), id, upcloudv9.ModifyDatabaseJSONRequestBody{ TerminationProtection: &b, }) if err != nil { return commands.HandleError(exec, msg, err) } + if res.JSON200 == nil { + return commands.HandleError(exec, msg, apierror.FromResponse(res.StatusCode(), res.Body)) + } } - err := svc.DeleteManagedDatabase(exec.Context(), &request.DeleteManagedDatabaseRequest{UUID: uuid}) + res, err := client.DeleteDatabaseWithResponse(exec.Context(), id) if err != nil { return commands.HandleError(exec, msg, err) } + if status := res.StatusCode(); status < 200 || status > 299 { + return commands.HandleError(exec, msg, apierror.FromResponse(status, res.Body)) + } if wait { - exec.PushProgressUpdateMessage(msg, fmt.Sprintf("Waiting for database service %s to be deleted", uuid)) - err = waitUntilDatabaseDeleted(exec, uuid) + exec.PushProgressUpdateMessage(msg, fmt.Sprintf("Waiting for database service %s to be deleted", uuidStr)) + err = waitUntilDatabaseDeleted(exec, client, id) if err != nil { return commands.HandleError(exec, msg, err) } @@ -83,21 +97,22 @@ func (c *deleteCommand) Execute(exec commands.Executor, arg string) (output.Outp return Delete(exec, arg, c.disableTerminationProtection.Value(), c.wait.Value()) } -func waitUntilDatabaseDeleted(exec commands.Executor, uuid string) error { - ticker := time.NewTicker(5 * time.Second) +func waitUntilDatabaseDeleted(exec commands.Executor, client *upcloudv9.ClientWithResponses, id uuid.UUID) error { + ticker := time.NewTicker(databasePollInterval) defer ticker.Stop() ctx := exec.Context() - svc := exec.All() - for i := 0; ; i++ { + for { select { case <-ticker.C: - _, err := svc.GetManagedDatabase(exec.Context(), &request.GetManagedDatabaseRequest{ - UUID: uuid, - }) + res, err := client.GetDatabaseWithResponse(ctx, id) if err != nil { - if utils.IsNotFoundError(err) { + return err + } + if res.JSON200 == nil { + err := apierror.FromResponse(res.StatusCode(), res.Body) + if apierror.IsNotFound(err) { return nil } diff --git a/internal/commands/database/delete_test.go b/internal/commands/database/delete_test.go index 90831a59a..40186b0fd 100644 --- a/internal/commands/database/delete_test.go +++ b/internal/commands/database/delete_test.go @@ -1,53 +1,133 @@ package database import ( + "context" + "net/http" "testing" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" "github.com/UpCloudLtd/upcloud-cli/v3/internal/config" smock "github.com/UpCloudLtd/upcloud-cli/v3/internal/mock" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/mockexecute" + "github.com/google/uuid" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/request" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -func TestDeleteCommand(t *testing.T) { - targetMethod := "DeleteManagedDatabase" +const deletedDatabaseUUID = "27fbd082-30b0-11eb-adc1-0242ac120004" - database := upcloud.ManagedDatabase{ - UUID: "27fbd082-30b0-11eb-adc1-0242ac120004", - Name: "test-database", +func TestDeleteCommand(t *testing.T) { + path := "/1.3/database/" + deletedDatabaseUUID + notFound := fakeResponse{ + status: http.StatusNotFound, + contentType: "application/problem+json", + body: `{"type": "https://developers.upcloud.com/1.3/errors#ERROR_SERVICE_NOT_FOUND", "title": "Service not found", "status": 404}`, } for _, test := range []struct { - name string - arg string - error string - req request.DeleteManagedDatabaseRequest + name string + args []string + responses map[string]fakeResponse + calls []string + error string + notFound bool }{ { - name: "delete with UUID", - arg: database.UUID, - req: request.DeleteManagedDatabaseRequest{UUID: database.UUID}, + name: "delete with UUID", + args: []string{deletedDatabaseUUID}, + responses: map[string]fakeResponse{"DELETE " + path: {status: http.StatusNoContent}}, + calls: []string{"DELETE"}, + }, + { + name: "disable termination protection before deleting", + args: []string{deletedDatabaseUUID, "--disable-termination-protection"}, + responses: map[string]fakeResponse{ + "PATCH " + path: {status: http.StatusOK, body: `{"uuid": "` + deletedDatabaseUUID + `", "termination_protection": false}`}, + "DELETE " + path: {status: http.StatusNoContent}, + }, + calls: []string{"PATCH", "DELETE"}, + }, + { + name: "failed termination protection update prevents deletion", + args: []string{deletedDatabaseUUID, "--disable-termination-protection"}, + responses: map[string]fakeResponse{ + "PATCH " + path: {status: http.StatusConflict, body: `{"type":"MODIFICATION_FAILED","title":"Could not disable termination protection","status":409}`}, + }, + calls: []string{"PATCH"}, + error: "Could not disable termination protection (type=MODIFICATION_FAILED, status=409)", + }, + { + name: "wait until the database is deleted", + args: []string{deletedDatabaseUUID, "--wait"}, + responses: map[string]fakeResponse{ + "DELETE " + path: {status: http.StatusNoContent}, + "GET " + path: notFound, + }, + calls: []string{"DELETE", "GET"}, + }, + { + name: "wait while database still exists", + args: []string{deletedDatabaseUUID, "--wait"}, + responses: map[string]fakeResponse{ + "DELETE " + path: {status: http.StatusNoContent}, + "GET " + path: {sequence: []fakeResponse{ + {status: http.StatusOK, body: `{"uuid":"` + deletedDatabaseUUID + `","state":"running"}`}, + notFound, + }}, + }, + calls: []string{"DELETE", "GET", "GET"}, + }, + { + name: "not found is reported as a not found error", + args: []string{deletedDatabaseUUID}, + responses: map[string]fakeResponse{"DELETE " + path: notFound}, + calls: []string{"DELETE"}, + error: "Service not found (type=https://developers.upcloud.com/1.3/errors#ERROR_SERVICE_NOT_FOUND, status=404)", + notFound: true, + }, + { + name: "invalid UUID", + args: []string{"not-a-uuid"}, + error: `invalid database UUID "not-a-uuid": invalid UUID length: 10`, }, } { t.Run(test.name, func(t *testing.T) { - mService := smock.Service{} - req := test.req - mService.On(targetMethod, &req).Return(nil) - + api := newFakeAPI(t, test.responses) conf := config.New() c := commands.BuildCommand(DeleteCommand(), nil, conf) + c.Cobra().SetArgs(test.args) - _, err := c.(commands.MultipleArgumentCommand).Execute(commands.NewExecutor(conf, &mService, conf.NewLogger("test")), test.arg) + _, err := mockexecute.MockExecuteWithV9(c, &smock.Service{}, api.client, conf) if test.error != "" { assert.EqualError(t, err, test.error) + assert.Equal(t, test.notFound, apierror.IsNotFound(err)) } else { - assert.NoError(t, err) - mService.AssertNumberOfCalls(t, targetMethod, 1) + require.NoError(t, err) + } + + var calls []string + for _, r := range api.all() { + calls = append(calls, r.Method) + } + assert.Equal(t, test.calls, calls) + if len(test.calls) > 0 && test.calls[0] == "PATCH" { + assert.JSONEq(t, `{"termination_protection": false}`, string(api.all()[0].Body)) } }) } } + +func TestWaitUntilDatabaseDeleted_Cancelled(t *testing.T) { + api := newFakeAPI(t, nil) + conf := config.New() + exec := commands.NewExecutor(conf, &smock.Service{}, conf.NewLogger("test")).WithV9Client(api.client) + conf.Cancel() + + err := waitUntilDatabaseDeleted(exec, api.client, uuid.MustParse(deletedDatabaseUUID)) + + assert.ErrorIs(t, err, context.Canceled) + assert.Empty(t, api.all()) +} diff --git a/internal/commands/database/fakeapi_test.go b/internal/commands/database/fakeapi_test.go new file mode 100644 index 000000000..68ea8b38c --- /dev/null +++ b/internal/commands/database/fakeapi_test.go @@ -0,0 +1,97 @@ +package database + +import ( + "io" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + "time" + + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" + "github.com/stretchr/testify/require" +) + +func init() { + databasePollInterval = 10 * time.Millisecond +} + +type apiRequest struct { + Method string + Path string + Query url.Values + Body []byte +} + +type fakeResponse struct { + status int + body string + contentType string + // sequence, when set, is served in order, repeating its last response. + sequence []fakeResponse +} + +// fakeAPI serves canned responses keyed by "METHOD /path" and records every request. +type fakeAPI struct { + mu sync.Mutex + requests []apiRequest + served map[string]int + client *upcloudv9.ClientWithResponses +} + +func newFakeAPI(t *testing.T, responses map[string]fakeResponse) *fakeAPI { + t.Helper() + api := &fakeAPI{served: map[string]int{}} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Errorf("reading request body: %v", err) + } + key := r.Method + " " + r.URL.Path + api.mu.Lock() + api.requests = append(api.requests, apiRequest{Method: r.Method, Path: r.URL.Path, Query: r.URL.Query(), Body: body}) + count := api.served[key] + api.served[key]++ + api.mu.Unlock() + + res, ok := responses[key] + if !ok { + t.Errorf("unexpected request %s", key) + w.WriteHeader(http.StatusInternalServerError) + return + } + if len(res.sequence) > 0 { + res = res.sequence[min(count, len(res.sequence)-1)] + } + contentType := res.contentType + if contentType == "" { + contentType = "application/json" + } + w.Header().Set("Content-Type", contentType) + w.WriteHeader(res.status) + _, _ = io.WriteString(w, res.body) + })) + t.Cleanup(server.Close) + + client, err := upcloudv9.NewClientWithResponses(server.URL) + require.NoError(t, err) + api.client = client + return api +} + +func (a *fakeAPI) all() []apiRequest { + a.mu.Lock() + defer a.mu.Unlock() + return append([]apiRequest(nil), a.requests...) +} + +func (a *fakeAPI) requestsTo(method, path string) []apiRequest { + var matching []apiRequest + for _, r := range a.all() { + if r.Method == method && r.Path == path { + matching = append(matching, r) + } + } + return matching +} diff --git a/internal/commands/database/list.go b/internal/commands/database/list.go index 022e2ee72..e56473898 100644 --- a/internal/commands/database/list.go +++ b/internal/commands/database/list.go @@ -1,12 +1,13 @@ package database import ( + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" "github.com/UpCloudLtd/upcloud-cli/v3/internal/format" "github.com/UpCloudLtd/upcloud-cli/v3/internal/output" "github.com/UpCloudLtd/upcloud-cli/v3/internal/paging" "github.com/UpCloudLtd/upcloud-cli/v3/internal/ui" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/request" + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" "github.com/spf13/pflag" ) @@ -30,28 +31,38 @@ func (s *listCommand) InitCommand() { // ExecuteWithoutArguments implements commands.NoArgumentCommand func (s *listCommand) ExecuteWithoutArguments(exec commands.Executor) (output.Output, error) { - svc := exec.All() - databases, err := svc.GetManagedDatabases(exec.Context(), &request.GetManagedDatabasesRequest{ - Page: s.Page(), + client, err := v9Client(exec) + if err != nil { + return nil, err + } + + limit, offset := s.LimitOffset() + res, err := client.ListDatabasesWithResponse(exec.Context(), &upcloudv9.ListDatabasesParams{ + Limit: &limit, + Offset: &offset, }) if err != nil { return nil, err } + if res.JSON200 == nil { + return nil, apierror.FromResponse(res.StatusCode(), res.Body) + } + databases := *res.JSON200 rows := []output.TableRow{} for _, db := range databases { - title := db.Title + title := deref(db.Title) if title == "" { - title = db.Name + title = deref(db.Name) } rows = append(rows, output.TableRow{ - db.UUID, + uuidString(db.Uuid), title, - db.Type, - db.Plan, - db.Zone, - db.State, + deref(db.Type), + deref(db.Plan), + deref(db.Zone), + deref(db.State), }) } diff --git a/internal/commands/database/list_test.go b/internal/commands/database/list_test.go index 6627478eb..584542829 100644 --- a/internal/commands/database/list_test.go +++ b/internal/commands/database/list_test.go @@ -1,6 +1,8 @@ package database import ( + "encoding/json" + "net/http" "testing" "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" @@ -8,51 +10,83 @@ import ( smock "github.com/UpCloudLtd/upcloud-cli/v3/internal/mock" "github.com/UpCloudLtd/upcloud-cli/v3/internal/mockexecute" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/request" "github.com/jedib0t/go-pretty/v6/text" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDatabaseListTitleFallback(t *testing.T) { text.DisableColors() - databases := []upcloud.ManagedDatabase{ - {UUID: "091f1afe-4ddd-4d43-afad-6aa3069cc7fe", Title: "service-name", Name: "hostname-prefix-1", State: "running"}, - {UUID: "091f1afe-4ddd-4d43-afad-6aa3069cc7fe", Name: "hostname-prefix-2", State: "running"}, - } + databases := `[ + {"uuid": "091f1afe-4ddd-4d43-afad-6aa3069cc7fe", "title": "service-name", "name": "hostname-prefix-1", "state": "running"}, + {"uuid": "091f1afe-4ddd-4d43-afad-6aa3069cc7fe", "name": "hostname-prefix-2", "state": "running"} + ]` for _, test := range []struct { - name string - args []string - page request.Page + name string + args []string + limit string + offset string }{ { - name: "default page", - page: request.Page{Size: 100, Number: 0}, + name: "default page", + limit: "100", + offset: "0", }, { - name: "limit and page args", - page: request.Page{Size: 18, Number: 19}, - args: []string{"--limit", "18", "--page", "19"}, + name: "limit and page args", + args: []string{"--limit", "18", "--page", "19"}, + limit: "18", + offset: "324", }, } { t.Run(test.name, func(t *testing.T) { - page := test.page - - mService := smock.Service{} - mService.On("GetManagedDatabases", &request.GetManagedDatabasesRequest{Page: &page}).Return(databases, nil) + api := newFakeAPI(t, map[string]fakeResponse{ + "GET /1.3/database": {status: http.StatusOK, body: databases}, + }) conf := config.New() command := commands.BuildCommand(ListCommand(), nil, conf) command.Cobra().SetArgs(test.args) - output, err := mockexecute.MockExecute(command, &mService, conf) + output, err := mockexecute.MockExecuteWithV9(command, &smock.Service{}, api.client, conf) - assert.NoError(t, err) + require.NoError(t, err) assert.Regexp(t, `UUID\s+Title\s+Type\s+Plan\s+Zone\s+State`, output) assert.Contains(t, output, "service-name") assert.NotContains(t, output, "hostname-prefix-1") assert.Contains(t, output, "hostname-prefix-2") + + requests := api.requestsTo(http.MethodGet, "/1.3/database") + require.Len(t, requests, 1) + assert.Equal(t, test.limit, requests[0].Query.Get("limit")) + assert.Equal(t, test.offset, requests[0].Query.Get("offset")) + }) + } +} + +func TestDatabaseListMachineReadableOutputUsesV9Response(t *testing.T) { + const id = "091f1afe-4ddd-4d43-afad-6aa3069cc7fe" + databases := `[{"uuid":"` + id + `","title":"service-name","type":"mysql","plan_components":{"compute":{"name":"rdb.standard.2CPU-8GB","node_count":2}}}]` + + for _, outputFormat := range []string{config.ValueOutputJSON, config.ValueOutputYAML} { + t.Run(outputFormat, func(t *testing.T) { + api := newFakeAPI(t, map[string]fakeResponse{"GET /1.3/database": {status: http.StatusOK, body: databases}}) + conf := config.New() + conf.Viper().Set(config.KeyOutput, outputFormat) + command := commands.BuildCommand(ListCommand(), nil, conf) + + out, err := mockexecute.MockExecuteWithV9(command, &smock.Service{}, api.client, conf) + require.NoError(t, err) + assert.Contains(t, out, "plan_components") + assert.Contains(t, out, "rdb.standard.2CPU-8GB") + if outputFormat == config.ValueOutputJSON { + var got []map[string]any + require.NoError(t, json.Unmarshal([]byte(out), &got)) + require.Len(t, got, 1) + assert.Equal(t, id, got[0]["uuid"]) + assert.Contains(t, got[0], "plan_components") + } }) } } diff --git a/internal/commands/database/plans.go b/internal/commands/database/plans.go index 5824d07a7..2f66f87a8 100644 --- a/internal/commands/database/plans.go +++ b/internal/commands/database/plans.go @@ -44,15 +44,19 @@ func (s *plansCommand) Execute(exec commands.Executor, serviceType string) (outp } computeShapes := make([]upcloud.ManagedDatabasePlanComputeShape, 0) + componentised := false for _, plan := range plans { if plan.Type == serviceType { computeShapes = plan.ComputeShapes + componentised = plan.Componentised } } var legacyPlans []upcloud.ManagedDatabaseServicePlan - if s.showLegacy.Value() { + // Engines without componentised plans only have legacy plans, so those plans + // are their normal catalog rather than optional historical entries. + if s.showLegacy.Value() || !componentised { dbType, err := svc.GetManagedDatabaseServiceType(exec.Context(), &request.GetManagedDatabaseServiceTypeRequest{Type: serviceType}) if err != nil { return nil, err @@ -76,11 +80,13 @@ func (s *plansCommand) Execute(exec commands.Executor, serviceType string) (outp }) for _, plan := range legacyPlans { + // Legacy plans report memory and storage in MB. + memoryGB, storageGB := plan.MemoryAmount/1024, plan.StorageSize/1024 computeShapes = append(computeShapes, upcloud.ManagedDatabasePlanComputeShape{ Compute: plan.Plan, Family: "legacy", CPU: plan.CoreNumber, - MemoryGB: plan.MemoryAmount, + MemoryGB: memoryGB, DynamicStorageSupported: false, NodeCounts: []int{plan.NodeCount}, Backups: []string{fmt.Sprintf("%d PITR days", plan.BackupConfig.MaxCount)}, @@ -89,7 +95,7 @@ func (s *plansCommand) Execute(exec commands.Executor, serviceType string) (outp DynamicMaxMultiplier: 0, TotalCapGiB: 0, Options: []upcloud.ManagedDatabasePlanStorageOption{ - {BaseGiB: plan.StorageSize, MaxGiB: plan.StorageSize}, + {BaseGiB: storageGB, MaxGiB: storageGB}, }, }, }) diff --git a/internal/commands/database/plans_test.go b/internal/commands/database/plans_test.go index fc02b9b71..ac08e9a7f 100644 --- a/internal/commands/database/plans_test.go +++ b/internal/commands/database/plans_test.go @@ -44,11 +44,11 @@ func TestDatabasePlans_SortedHumanOutput(t *testing.T) { //nolint:staticcheck // using ManagedDatabaseBackupConfig for legacy plans legacyPg := upcloud.ManagedDatabaseType{ ServicePlans: []upcloud.ManagedDatabaseServicePlan{ - {Plan: "test-plan-5", NodeCount: 3, CoreNumber: 16, MemoryAmount: 128, StorageSize: 2048, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 30}}, - {Plan: "test-plan-3", NodeCount: 1, CoreNumber: 2, MemoryAmount: 16, StorageSize: 256, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 15}}, - {Plan: "test-plan-1", NodeCount: 1, CoreNumber: 1, MemoryAmount: 8, StorageSize: 2048, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 3}}, - {Plan: "test-plan-2", NodeCount: 1, CoreNumber: 2, MemoryAmount: 4, StorageSize: 2048, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 7}}, - {Plan: "test-plan-4", NodeCount: 3, CoreNumber: 16, MemoryAmount: 128, StorageSize: 1024, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 20}}, + {Plan: "test-plan-5", NodeCount: 3, CoreNumber: 16, MemoryAmount: 131072, StorageSize: 2097152, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 30}}, + {Plan: "test-plan-3", NodeCount: 1, CoreNumber: 2, MemoryAmount: 16384, StorageSize: 262144, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 15}}, + {Plan: "test-plan-1", NodeCount: 1, CoreNumber: 1, MemoryAmount: 8192, StorageSize: 2097152, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 3}}, + {Plan: "test-plan-2", NodeCount: 1, CoreNumber: 2, MemoryAmount: 4096, StorageSize: 102400, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 7}}, + {Plan: "test-plan-4", NodeCount: 3, CoreNumber: 16, MemoryAmount: 131072, StorageSize: 1048576, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 20}}, }, } @@ -74,8 +74,36 @@ func TestDatabasePlans_SortedHumanOutput(t *testing.T) { assert.NotContains(t, output, ", 50, 100-200") assert.Contains(t, output, "3 PITR days") assert.Contains(t, output, "legacy") + assert.Regexp(t, `test-plan-2\s+legacy\s+2\s+4\s+1\s+100\s+7 PITR days`, output) + assert.NotContains(t, output, "4096") + assert.NotContains(t, output, "102400") assert.Less(t, strings.Index(output, "test-plan-1"), strings.Index(output, "test-plan-2")) assert.Less(t, strings.Index(output, "test-plan-2"), strings.Index(output, "test-plan-3")) assert.Less(t, strings.Index(output, "test-plan-3"), strings.Index(output, "test-plan-4")) assert.Less(t, strings.Index(output, "test-plan-4"), strings.Index(output, "test-plan-5")) } + +func TestDatabasePlans_LegacyOnlyTypeShowsPlansByDefault(t *testing.T) { + text.DisableColors() + plans := []upcloud.ManagedDatabasePlanServiceType{ + {Type: "pg", Componentised: true}, + {Type: "mysql", Componentised: true}, + } + //nolint:staticcheck // using ManagedDatabaseBackupConfig for legacy plans + legacyOpenSearch := upcloud.ManagedDatabaseType{ServicePlans: []upcloud.ManagedDatabaseServicePlan{ + {Plan: "1x2xCPU-4GB-80GB-1D", NodeCount: 1, CoreNumber: 2, MemoryAmount: 4096, StorageSize: 81920, BackupConfig: upcloud.ManagedDatabaseBackupConfig{MaxCount: 1}}, + }} + + mService := smock.Service{} + mService.On("GetManagedDatabasePlans", mock.Anything).Return(plans, nil) + mService.On("GetManagedDatabaseServiceType", mock.Anything).Return(&legacyOpenSearch, nil) + conf := config.New() + command := commands.BuildCommand(PlansCommand(), nil, conf) + command.Cobra().SetArgs([]string{"opensearch"}) + + out, err := mockexecute.MockExecute(command, &mService, conf) + + assert.NoError(t, err) + assert.Contains(t, out, "1x2xCPU-4GB-80GB-1D") + mService.AssertNumberOfCalls(t, "GetManagedDatabaseServiceType", 1) +} diff --git a/internal/commands/database/show.go b/internal/commands/database/show.go index 06d802cd2..f8b33cd95 100644 --- a/internal/commands/database/show.go +++ b/internal/commands/database/show.go @@ -1,6 +1,7 @@ package database import ( + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" "github.com/UpCloudLtd/upcloud-cli/v3/internal/completion" "github.com/UpCloudLtd/upcloud-cli/v3/internal/format" @@ -8,8 +9,7 @@ import ( "github.com/UpCloudLtd/upcloud-cli/v3/internal/output" "github.com/UpCloudLtd/upcloud-cli/v3/internal/resolver" "github.com/UpCloudLtd/upcloud-cli/v3/internal/ui" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/request" + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" ) // ShowCommand creates the "database show" command @@ -32,80 +32,104 @@ type showCommand struct { } // Execute implements commands.MultipleArgumentCommand -func (s *showCommand) Execute(exec commands.Executor, uuid string) (output.Output, error) { - svc := exec.All() - db, err := svc.GetManagedDatabase(exec.Context(), &request.GetManagedDatabaseRequest{UUID: uuid}) +func (s *showCommand) Execute(exec commands.Executor, uuidStr string) (output.Output, error) { + client, err := v9Client(exec) if err != nil { return nil, err } + id, err := parseDatabaseUUID(uuidStr) + if err != nil { + return nil, err + } + + res, err := client.GetDatabaseWithResponse(exec.Context(), id) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apierror.FromResponse(res.StatusCode(), res.Body) + } + db := res.JSON200 + dbType := deref(db.Type) nodeRows := []output.TableRow{} - for _, node := range db.NodeStates { + for _, node := range deref(db.NodeStates) { nodeRows = append(nodeRows, output.TableRow{ - node.Name, - node.Role, - node.State, + deref(node.Name), + deref(node.Role), + deref(node.State), }) } componentsRows := []output.TableRow{} - for _, component := range db.Components { + for _, component := range deref(db.Components) { componentsRows = append(componentsRows, output.TableRow{ - component.Component, - component.Host, - component.Port, - component.Route, - component.Usage, + deref(component.Component), + deref(component.Host), + deref(component.Port), + deref(component.Route), + deref(component.Usage), }) } + maintenance := deref(db.Maintenance) detailSections := []output.DetailSection{ { Title: "Overview:", Rows: []output.DetailRow{ - {Title: "UUID:", Value: db.UUID, Colour: ui.DefaultUUUIDColours}, - {Title: "Title:", Value: db.Title}, - {Title: "Name:", Value: db.Name}, - {Title: "Type:", Value: prettyDatabaseType(db.Type)}, + {Title: "UUID:", Value: uuidString(db.Uuid), Colour: ui.DefaultUUUIDColours}, + {Title: "Title:", Value: deref(db.Title)}, + {Title: "Name:", Value: deref(db.Name)}, + {Title: "Type:", Value: prettyDatabaseType(dbType)}, {Title: "Version:", Value: getVersion(db), Format: format.PossiblyUnknownString}, - {Title: "Plan:", Value: db.Plan}, - {Title: "Zone:", Value: db.Zone}, - {Title: "State:", Value: db.State, Format: format.DatabaseState}, - {Title: "Termination protection:", Value: db.TerminationProtection, Format: format.Boolean}, + {Title: "Plan:", Value: deref(db.Plan)}, + {Title: "Zone:", Value: deref(db.Zone)}, + {Title: "State:", Value: deref(db.State), Format: format.DatabaseState}, + {Title: "Termination protection:", Value: deref(db.TerminationProtection), Format: format.Boolean}, }, }, - { + } + + if section, ok := planComponentsSection(db.PlanComponents); ok { + detailSections = append(detailSections, section) + } + + detailSections = append(detailSections, + output.DetailSection{ Title: "Maintenance schedule:", Rows: []output.DetailRow{ - {Title: "Weekday:", Value: db.Maintenance.DayOfWeek}, - {Title: "Time:", Value: db.Maintenance.Time}, + {Title: "Weekday:", Value: deref(maintenance.Dow)}, + {Title: "Time:", Value: deref(maintenance.Time)}, }, }, - { + output.DetailSection{ Title: "Authentication:", Rows: []output.DetailRow{ - {Title: "Service URI:", Value: db.ServiceURI}, - {Title: "Database name:", Value: db.ServiceURIParams.DatabaseName}, - {Title: "Host:", Value: db.ServiceURIParams.Host}, - {Title: "Password:", Value: db.ServiceURIParams.Password}, - {Title: "Port:", Value: db.ServiceURIParams.Port}, - {Title: "SSL mode:", Value: db.ServiceURIParams.SSLMode}, - {Title: "User:", Value: db.ServiceURIParams.User}, + {Title: "Service URI:", Value: deref(db.ServiceUri)}, + {Title: "Database name:", Value: mapString(db.ServiceUriParams, "dbname")}, + {Title: "Host:", Value: mapString(db.ServiceUriParams, "host")}, + {Title: "Password:", Value: mapString(db.ServiceUriParams, "password")}, + {Title: "Port:", Value: mapString(db.ServiceUriParams, "port")}, + {Title: "SSL mode:", Value: mapString(db.ServiceUriParams, "ssl_mode")}, + {Title: "User:", Value: mapString(db.ServiceUriParams, "user")}, }, }, - } + ) - if db.Type == upcloud.ManagedDatabaseServiceTypeOpenSearch { - acl, err := svc.GetManagedDatabaseAccessControl(exec.Context(), &request.GetManagedDatabaseAccessControlRequest{ServiceUUID: uuid}) + if dbType == string(upcloudv9.DatabaseServiceTypeOpensearch) { + acl, err := client.GetDatabaseAccessControlWithResponse(exec.Context(), id) if err != nil { return nil, err } + if acl.JSON200 == nil { + return nil, apierror.FromResponse(acl.StatusCode(), acl.Body) + } detailSections = append(detailSections, output.DetailSection{ Title: "Access control settings:", Rows: []output.DetailRow{ - {Title: "Access control:", Value: acl.ACLsEnabled, Format: format.Boolean}, - {Title: "Extended access control:", Value: acl.ExtendedACLsEnabled, Format: format.Boolean}, + {Title: "Access control:", Value: deref(acl.JSON200.AccessControl), Format: format.Boolean}, + {Title: "Extended access control:", Value: deref(acl.JSON200.ExtendedAccessControl), Format: format.Boolean}, }, }) } @@ -119,7 +143,9 @@ func (s *showCommand) Execute(exec commands.Executor, uuid string) (output.Outpu Sections: detailSections, }, }, - labels.GetLabelsSectionWithResourceType(db.Labels, "database"), + labels.LabelsSection(deref(db.Labels), func(l upcloudv9.DatabaseLabelInformationResponse) (string, string) { + return deref(l.Key), deref(l.Value) + }, "database"), output.CombinedSection{ Title: "Nodes:", Contents: output.Table{ @@ -148,33 +174,50 @@ func (s *showCommand) Execute(exec commands.Executor, uuid string) (output.Outpu }, nil } -func getVersion(db *upcloud.ManagedDatabase) string { +func planComponentsSection(pc *upcloudv9.DatabasePlanComponentsResponse) (output.DetailSection, bool) { + if pc == nil || pc.Compute == nil || pc.Compute.Name == nil { + return output.DetailSection{}, false + } + + return output.DetailSection{ + Title: "Plan components:", + Rows: []output.DetailRow{ + {Title: "Compute:", Value: *pc.Compute.Name}, + {Title: "Node count:", Value: deref(pc.Compute.NodeCount)}, + {Title: "Storage per node (GiB):", Value: deref(deref(pc.Storage).TotalGib)}, + {Title: "Backups:", Value: string(deref(deref(pc.Backups).Name))}, + }, + }, true +} + +var versionMetadataKeys = map[string]string{ + "mysql": "mysql_version", + "opensearch": "opensearch_version", + "pg": "pg_version", + "valkey": "valkey_version", +} + +func getVersion(db *upcloudv9.DatabaseServiceInformationResponse) string { if db == nil || db.Metadata == nil { return "" } - switch db.Type { - case "mysql": - return db.Metadata.MySQLVersion - case "opensearch": - return db.Metadata.OpenSearchVersion - case "pg": - return db.Metadata.PGVersion - case "valkey": - return db.Metadata.ValkeyVersion + key, ok := versionMetadataKeys[deref(db.Type)] + if !ok { + return "" } - return "" + return mapString(db.Metadata, key) } -func prettyDatabaseType(serviceType upcloud.ManagedDatabaseServiceType) string { - switch serviceType { - case upcloud.ManagedDatabaseServiceTypeMySQL: +func prettyDatabaseType(serviceType string) string { + switch upcloudv9.DatabaseServiceType(serviceType) { + case upcloudv9.DatabaseServiceTypeMysql: return "MySQL" - case upcloud.ManagedDatabaseServiceTypeOpenSearch: + case upcloudv9.DatabaseServiceTypeOpensearch: return "OpenSearch" - case upcloud.ManagedDatabaseServiceTypePostgreSQL: + case upcloudv9.DatabaseServiceTypePg: return "PostgreSQL" default: - return string(serviceType) + return serviceType } } diff --git a/internal/commands/database/show_test.go b/internal/commands/database/show_test.go index ecfabc790..3a6e799df 100644 --- a/internal/commands/database/show_test.go +++ b/internal/commands/database/show_test.go @@ -1,17 +1,30 @@ package database import ( + "encoding/json" + "net/http" "testing" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/config" + smock "github.com/UpCloudLtd/upcloud-cli/v3/internal/mock" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/mockexecute" + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" + + "github.com/jedib0t/go-pretty/v6/text" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +const shownDatabaseUUID = "9a8effcb-80e6-4a63-a7e5-066a6d093c14" + func TestGetVersion(t *testing.T) { + pg, valkey := "pg", "valkey" for _, test := range []struct { name string expected string - db *upcloud.ManagedDatabase + db *upcloudv9.DatabaseServiceInformationResponse }{ { name: "nil database", @@ -20,20 +33,20 @@ func TestGetVersion(t *testing.T) { }, { name: "nil metadata", expected: "", - db: &upcloud.ManagedDatabase{Metadata: nil}, + db: &upcloudv9.DatabaseServiceInformationResponse{Metadata: nil}, }, { name: "pg", expected: "15", - db: &upcloud.ManagedDatabase{ - Type: upcloud.ManagedDatabaseServiceTypePostgreSQL, - Metadata: &upcloud.ManagedDatabaseMetadata{PGVersion: "15"}, + db: &upcloudv9.DatabaseServiceInformationResponse{ + Type: &pg, + Metadata: &map[string]any{"pg_version": "15"}, }, }, { name: "valkey", expected: "8.1.5", - db: &upcloud.ManagedDatabase{ - Type: upcloud.ManagedDatabaseServiceTypeValkey, - Metadata: &upcloud.ManagedDatabaseMetadata{ValkeyVersion: "8.1.5"}, + db: &upcloudv9.DatabaseServiceInformationResponse{ + Type: &valkey, + Metadata: &map[string]any{"valkey_version": "8.1.5"}, }, }, } { @@ -43,3 +56,121 @@ func TestGetVersion(t *testing.T) { }) } } + +func TestShowCommand(t *testing.T) { + text.DisableColors() + id := shownDatabaseUUID + database := `{ + "uuid": "` + id + `", "title": "my-pg", "name": "my-pg-prefix", "type": "pg", "zone": "fi-hel1", "state": "running", + "plan": "rdb.standard.2x-2CPU-8GB-120GB-regular", "termination_protection": true, + "plan_components": {"compute": {"name": "rdb.standard.2CPU-8GB", "node_count": 2, "cpu": 2, "memory_gb": 8}, "storage": {"total_gib": 120}, "backups": {"name": "regular"}}, + "metadata": {"pg_version": "16"}, + "maintenance": {"dow": "sunday", "time": "05:00:00"}, + "service_uri_params": {"dbname": "defaultdb", "host": "my-pg.example.com", "port": 11550, "user": "upadmin"}, + "labels": [{"key": "env", "value": "dev"}], + "node_states": [{"name": "my-pg-1", "role": "master", "state": "running"}], + "components": [{"component": "pg", "host": "my-pg.example.com", "port": 11550, "route": "dynamic", "usage": "primary"}] + }` + + api := newFakeAPI(t, map[string]fakeResponse{ + "GET /1.3/database/" + id: {status: http.StatusOK, body: database}, + }) + conf := config.New() + c := commands.BuildCommand(ShowCommand(), nil, conf) + c.Cobra().SetArgs([]string{id}) + + out, err := mockexecute.MockExecuteWithV9(c, &smock.Service{}, api.client, conf) + require.NoError(t, err) + + for _, pattern := range []string{ + `UUID:\s+` + id, + `Type:\s+PostgreSQL`, + `Version:\s+16`, + `Plan:\s+rdb.standard.2x-2CPU-8GB-120GB-regular`, + `Termination protection:\s+yes`, + `Plan components:`, + `Compute:\s+rdb.standard.2CPU-8GB`, + `Node count:\s+2`, + `Storage per node \(GiB\):\s+120`, + `Backups:\s+regular`, + `Weekday:\s+sunday`, + `Port:\s+11550`, + `env\s+dev`, + `my-pg-1\s+master\s+running`, + } { + assert.Regexp(t, pattern, out) + } +} + +func TestShowCommand_NotFound(t *testing.T) { + id := shownDatabaseUUID + api := newFakeAPI(t, map[string]fakeResponse{ + "GET /1.3/database/" + id: {status: http.StatusNotFound, contentType: "application/json", body: `{"error": {"error_code": "SERVICE_NOT_FOUND", "error_message": "Service not found"}}`}, + }) + conf := config.New() + c := commands.BuildCommand(ShowCommand(), nil, conf) + c.Cobra().SetArgs([]string{id}) + + _, err := mockexecute.MockExecuteWithV9(c, &smock.Service{}, api.client, conf) + assert.EqualError(t, err, "Service not found (type=SERVICE_NOT_FOUND, status=404)") + assert.True(t, apierror.IsNotFound(err)) +} + +func TestShowCommand_MySQL(t *testing.T) { + id := shownDatabaseUUID + api := newFakeAPI(t, map[string]fakeResponse{ + "GET /1.3/database/" + id: {status: http.StatusOK, body: `{"uuid":"` + id + `","type":"mysql","metadata":{"mysql_version":"8"},"state":"running"}`}, + }) + conf := config.New() + c := commands.BuildCommand(ShowCommand(), nil, conf) + c.Cobra().SetArgs([]string{id}) + + out, err := mockexecute.MockExecuteWithV9(c, &smock.Service{}, api.client, conf) + require.NoError(t, err) + assert.Regexp(t, `Type:\s+MySQL`, out) + assert.Regexp(t, `Version:\s+8`, out) +} + +func TestShowCommand_MachineReadableOutputUsesV9Response(t *testing.T) { + id := shownDatabaseUUID + response := `{"uuid":"` + id + `","title":"my-pg","type":"pg","plan_components":{"compute":{"name":"rdb.standard.2CPU-8GB","node_count":2}}}` + + for _, outputFormat := range []string{config.ValueOutputJSON, config.ValueOutputYAML} { + t.Run(outputFormat, func(t *testing.T) { + api := newFakeAPI(t, map[string]fakeResponse{"GET /1.3/database/" + id: {status: http.StatusOK, body: response}}) + conf := config.New() + conf.Viper().Set(config.KeyOutput, outputFormat) + c := commands.BuildCommand(ShowCommand(), nil, conf) + c.Cobra().SetArgs([]string{id}) + + out, err := mockexecute.MockExecuteWithV9(c, &smock.Service{}, api.client, conf) + require.NoError(t, err) + assert.Contains(t, out, "plan_components") + assert.Contains(t, out, "rdb.standard.2CPU-8GB") + if outputFormat == config.ValueOutputJSON { + var got map[string]any + require.NoError(t, json.Unmarshal([]byte(out), &got)) + assert.Equal(t, id, got["uuid"]) + assert.Contains(t, got, "plan_components") + } + }) + } +} + +func TestShowCommand_OpenSearchAccessControl(t *testing.T) { + text.DisableColors() + id := shownDatabaseUUID + api := newFakeAPI(t, map[string]fakeResponse{ + "GET /1.3/database/" + id: {status: http.StatusOK, body: `{"uuid": "` + id + `", "type": "opensearch", "state": "running"}`}, + "GET /1.3/database/" + id + "/access-control": {status: http.StatusOK, body: `{"access_control": true, "extended_access_control": false}`}, + }) + conf := config.New() + c := commands.BuildCommand(ShowCommand(), nil, conf) + c.Cobra().SetArgs([]string{id}) + + out, err := mockexecute.MockExecuteWithV9(c, &smock.Service{}, api.client, conf) + require.NoError(t, err) + assert.Regexp(t, `Type:\s+OpenSearch`, out) + assert.Regexp(t, `Access control:\s+yes`, out) + assert.Regexp(t, `Extended access control:\s+no`, out) +} diff --git a/internal/commands/database/v9.go b/internal/commands/database/v9.go new file mode 100644 index 000000000..58aaadb86 --- /dev/null +++ b/internal/commands/database/v9.go @@ -0,0 +1,154 @@ +package database + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "maps" + "net/http" + "slices" + "strings" + "time" + + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" + "github.com/google/uuid" +) + +const ( + databaseStateRunning = "running" + databaseStateError = "error" +) + +// databasePollInterval matches the v8 SDK wait helpers. +var databasePollInterval = 5 * time.Second + +func v9Client(exec commands.Executor) (*upcloudv9.ClientWithResponses, error) { + client := exec.V9() + if client == nil { + return nil, errors.New("UpCloud API v9 client is not available, run with --debug for details") + } + return client, nil +} + +func deref[T any](v *T) T { + if v == nil { + var zero T + return zero + } + return *v +} + +func parseDatabaseUUID(value string) (uuid.UUID, error) { + id, err := uuid.Parse(value) + if err != nil { + return id, fmt.Errorf("invalid database UUID %q: %w", value, err) + } + return id, nil +} + +func uuidString(id *uuid.UUID) string { + if id == nil { + return "" + } + return id.String() +} + +func mapString(m *map[string]any, key string) string { + if m == nil { + return "" + } + switch v := (*m)[key].(type) { + case nil: + return "" + case string: + return v + default: + return fmt.Sprint(v) + } +} + +type propertySchema struct { + // Type is a JSON schema type: a string, or a list such as ["string", "null"]. + Type any `json:"type"` +} + +func (p propertySchema) allowsString() bool { + switch t := p.Type.(type) { + case string: + return t == "string" + case []any: + return slices.Contains(t, any("string")) + } + return false +} + +// getServiceTypeProperties decodes the response itself, as the generated v9 model cannot decode list-valued property types. +func getServiceTypeProperties(ctx context.Context, client *upcloudv9.ClientWithResponses, dbType string) (map[string]propertySchema, error) { + res, err := client.GetDatabaseType(ctx, upcloudv9.GetDatabaseTypeServiceTypeName(dbType)) + if err != nil { + return nil, err + } + defer res.Body.Close() + + body, err := io.ReadAll(res.Body) + if err != nil { + return nil, err + } + if res.StatusCode != http.StatusOK { + return nil, apierror.FromResponse(res.StatusCode, body) + } + + var serviceType struct { + Properties map[string]propertySchema `json:"properties"` + } + if err := json.Unmarshal(body, &serviceType); err != nil { + return nil, fmt.Errorf("cannot parse database type %s: %w", dbType, err) + } + return serviceType.Properties, nil +} + +// waitForDatabaseState polls like the v8 SDK, retrying up to three consecutive server errors. +func waitForDatabaseState(ctx context.Context, client *upcloudv9.ClientWithResponses, id uuid.UUID, state string) error { + ticker := time.NewTicker(databasePollInterval) + defer ticker.Stop() + + serverErrors := 0 + for { + select { + case <-ctx.Done(): + return ctx.Err() + case <-ticker.C: + res, err := client.GetDatabaseWithResponse(ctx, id) + if err != nil { + return err + } + if res.JSON200 == nil { + if res.StatusCode() >= http.StatusInternalServerError && serverErrors < 3 { + serverErrors++ + continue + } + return apierror.FromResponse(res.StatusCode(), res.Body) + } + serverErrors = 0 + + switch deref(res.JSON200.State) { + case state: + return nil + case databaseStateError: + return stateError(deref(res.JSON200.StateError)) + } + } + } +} + +func stateError(stateErrors map[string]string) error { + details := make([]string, 0, len(stateErrors)) + for _, key := range slices.Sorted(maps.Keys(stateErrors)) { + details = append(details, fmt.Sprintf("%s (%s)", stateErrors[key], key)) + } + return fmt.Errorf("managed database entered error state: %s", strings.Join(details, ", ")) +} diff --git a/internal/commands/database/v9_test.go b/internal/commands/database/v9_test.go new file mode 100644 index 000000000..28f8088f9 --- /dev/null +++ b/internal/commands/database/v9_test.go @@ -0,0 +1,91 @@ +package database + +import ( + "context" + "net/http" + "testing" + + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestWaitForDatabaseState(t *testing.T) { + id := uuid.MustParse("5c2f1f0e-7d1a-4f7e-9f0b-2a6c1d3e4b5a") + path := "GET /1.3/database/" + id.String() + serverError := fakeResponse{status: http.StatusBadGateway, contentType: "text/plain", body: "bad gateway"} + rebuilding := fakeResponse{status: http.StatusOK, body: `{"state": "rebuilding"}`} + running := fakeResponse{status: http.StatusOK, body: `{"state": "running"}`} + + for _, test := range []struct { + name string + sequence []fakeResponse + error string + notFound bool + polls int + }{ + { + name: "returns when the state is reached", + sequence: []fakeResponse{rebuilding, rebuilding, running}, + polls: 3, + }, + { + name: "retries up to three consecutive server errors", + sequence: []fakeResponse{serverError, serverError, serverError, running}, + polls: 4, + }, + { + name: "fails on the fourth consecutive server error", + sequence: []fakeResponse{serverError, serverError, serverError, serverError}, + error: "bad gateway (type=, status=502)", + polls: 4, + }, + { + name: "fails when the database enters the error state", + sequence: []fakeResponse{rebuilding, {status: http.StatusOK, body: `{"state": "error", "state_error": {"init": "failed", "backup": "missing"}}`}}, + error: "managed database entered error state: missing (backup), failed (init)", + polls: 2, + }, + { + name: "fails when the database is not found", + sequence: []fakeResponse{{status: http.StatusNotFound, contentType: "application/problem+json", body: `{"type": "SERVICE_NOT_FOUND", "title": "Service not found", "status": 404}`}}, + error: "Service not found (type=SERVICE_NOT_FOUND, status=404)", + notFound: true, + polls: 1, + }, + } { + t.Run(test.name, func(t *testing.T) { + api := newFakeAPI(t, map[string]fakeResponse{path: {sequence: test.sequence}}) + + err := waitForDatabaseState(context.Background(), api.client, id, databaseStateRunning) + + if test.error == "" { + require.NoError(t, err) + } else { + require.EqualError(t, err, test.error) + assert.Equal(t, test.notFound, apierror.IsNotFound(err)) + } + assert.Len(t, api.all(), test.polls) + }) + } +} + +func TestPropertySchemaAllowsString(t *testing.T) { + assert.True(t, propertySchema{Type: "string"}.allowsString()) + assert.True(t, propertySchema{Type: []any{"string", "null"}}.allowsString()) + assert.False(t, propertySchema{Type: "integer"}.allowsString()) + assert.False(t, propertySchema{Type: []any{"integer", "null"}}.allowsString()) + assert.False(t, propertySchema{}.allowsString()) +} + +func TestWaitForDatabaseState_Cancelled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + api := newFakeAPI(t, nil) + + err := waitForDatabaseState(ctx, api.client, uuid.MustParse("5c2f1f0e-7d1a-4f7e-9f0b-2a6c1d3e4b5a"), databaseStateRunning) + + assert.ErrorIs(t, err, context.Canceled) + assert.Empty(t, api.all()) +} diff --git a/internal/commands/stack/starterkit/deploy.go b/internal/commands/stack/starterkit/deploy.go index 1b1d97252..0a5f385ad 100644 --- a/internal/commands/stack/starterkit/deploy.go +++ b/internal/commands/stack/starterkit/deploy.go @@ -156,7 +156,7 @@ func (s *deployStarterKitCommand) deploy(exec commands.Executor) (string, error) msg = fmt.Sprintf("Waiting for database with UUID: %s to be ready ", db.UUID) exec.PushProgressStarted(msg) - database.WaitForManagedDatabaseState(db.UUID, upcloud.ManagedDatabaseStateRunning, exec, msg) + database.WaitForManagedDatabaseState(db.UUID, string(upcloud.ManagedDatabaseStateRunning), exec, msg) db, err = exec.All().GetManagedDatabase(exec.Context(), &request.GetManagedDatabaseRequest{ UUID: db.UUID, }) diff --git a/internal/format/database.go b/internal/format/database.go index 1162a1847..baf7eee9a 100644 --- a/internal/format/database.go +++ b/internal/format/database.go @@ -5,14 +5,13 @@ import ( "strings" "github.com/UpCloudLtd/upcloud-cli/v3/internal/ui" - "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" "github.com/jedib0t/go-pretty/v6/text" ) // databaseStateColour maps database states to colours -func databaseStateColour(state upcloud.ManagedDatabaseState) text.Colors { +func databaseStateColour(state string) text.Colors { switch state { - case upcloud.ManagedDatabaseStateRunning: + case "running": return text.Colors{text.FgGreen} case "rebuilding", "rebalancing": return text.Colors{text.FgYellow} diff --git a/internal/labels/output.go b/internal/labels/output.go index 066f60470..ad073b55e 100644 --- a/internal/labels/output.go +++ b/internal/labels/output.go @@ -9,9 +9,15 @@ import ( // GetLabelsSectionWithResourceType returns labels table as output.CombinedSection with resource type in the empty message. func GetLabelsSectionWithResourceType(labels []upcloud.Label, resourceType string) output.CombinedSection { + return LabelsSection(labels, func(l upcloud.Label) (string, string) { return l.Key, l.Value }, resourceType) +} + +// LabelsSection returns labels of any SDK type as output.CombinedSection, using keyValue to read each label. +func LabelsSection[T any](labels []T, keyValue func(T) (key, value string), resourceType string) output.CombinedSection { var rows []output.TableRow - for _, i := range labels { - rows = append(rows, output.TableRow{i.Key, i.Value}) + for _, label := range labels { + key, value := keyValue(label) + rows = append(rows, output.TableRow{key, value}) } return output.CombinedSection{ diff --git a/internal/labels/process.go b/internal/labels/process.go index c565b693a..260286e53 100644 --- a/internal/labels/process.go +++ b/internal/labels/process.go @@ -22,14 +22,19 @@ func StringsToUpCloudLabelSlice(in []string) (*upcloud.LabelSlice, error) { } func StringsToSliceOfLabels(in []string) ([]upcloud.Label, error) { - labelSlice := make([]upcloud.Label, 0) + return StringsToLabels(in, func(key, value string) upcloud.Label { return upcloud.Label{Key: key, Value: value} }) +} + +// StringsToLabels parses key=value strings into labels of any SDK type built by newLabel. +func StringsToLabels[T any](in []string, newLabel func(key, value string) T) ([]T, error) { + labelSlice := make([]T, 0, len(in)) for _, l := range in { label, err := stringToLabel(l) if err != nil { return nil, err } - labelSlice = append(labelSlice, label) + labelSlice = append(labelSlice, newLabel(label.Key, label.Value)) } return labelSlice, nil diff --git a/internal/mockexecute/mockexecute.go b/internal/mockexecute/mockexecute.go index 417531174..f605a698f 100644 --- a/internal/mockexecute/mockexecute.go +++ b/internal/mockexecute/mockexecute.go @@ -8,10 +8,15 @@ import ( "github.com/UpCloudLtd/upcloud-cli/v3/internal/output" "github.com/UpCloudLtd/upcloud-cli/v3/internal/service" + upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" "github.com/spf13/cobra" ) func MockExecute(command commands.Command, service service.AllServices, conf *config.Config) (string, error) { + return MockExecuteWithV9(command, service, nil, conf) +} + +func MockExecuteWithV9(command commands.Command, service service.AllServices, v9Client *upcloudv9.ClientWithResponses, conf *config.Config) (string, error) { buf := bytes.NewBuffer(nil) command.Cobra().SetErr(buf) command.Cobra().SetOut(buf) @@ -22,15 +27,15 @@ func MockExecute(command commands.Command, service service.AllServices, conf *co } command.Cobra().RunE = func(_ *cobra.Command, args []string) error { - return mockRunE(command, service, conf, args) + return mockRunE(command, service, v9Client, conf, args) } err := command.Cobra().Execute() return buf.String(), err } -func mockRunE(command commands.Command, service service.AllServices, conf *config.Config, args []string) error { - executor := commands.NewExecutor(conf, service, conf.NewLogger("test")) +func mockRunE(command commands.Command, service service.AllServices, v9Client *upcloudv9.ClientWithResponses, conf *config.Config, args []string) error { + executor := commands.NewExecutor(conf, service, conf.NewLogger("test")).WithV9Client(v9Client) var err error var out output.Output diff --git a/internal/paging/paging.go b/internal/paging/paging.go index d9e745385..0d6a288cc 100644 --- a/internal/paging/paging.go +++ b/internal/paging/paging.go @@ -25,3 +25,9 @@ func (pp *PageParameters) Page() *request.Page { Size: pp.size, } } + +// LimitOffset returns the page as limit and offset query values, computed the same way as the v8 SDK. +func (pp *PageParameters) LimitOffset() (limit, offset int) { + limit = max(pp.size, 0) + return limit, (max(pp.number, 1) - 1) * limit +} diff --git a/internal/utils/errors.go b/internal/utils/errors.go index b2db77636..466ebf61d 100644 --- a/internal/utils/errors.go +++ b/internal/utils/errors.go @@ -4,10 +4,15 @@ import ( "errors" "net/http" + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" ) func IsNotFoundError(err error) bool { + if apierror.IsNotFound(err) { + return true + } + var ucErr *upcloud.Problem if errors.As(err, &ucErr) && ucErr.Status == http.StatusNotFound { return true diff --git a/internal/utils/errors_test.go b/internal/utils/errors_test.go new file mode 100644 index 000000000..689209da2 --- /dev/null +++ b/internal/utils/errors_test.go @@ -0,0 +1,31 @@ +package utils + +import ( + "fmt" + "net/http" + "testing" + + "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" + "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" + "github.com/stretchr/testify/assert" +) + +func TestIsNotFoundError(t *testing.T) { + for _, test := range []struct { + name string + err error + expected bool + }{ + {name: "v8 not found", err: &upcloud.Problem{Status: http.StatusNotFound}, expected: true}, + {name: "wrapped v8 not found", err: fmt.Errorf("wrapped: %w", &upcloud.Problem{Status: http.StatusNotFound}), expected: true}, + {name: "v9 not found", err: &apierror.Problem{Status: http.StatusNotFound}, expected: true}, + {name: "wrapped v9 not found", err: fmt.Errorf("wrapped: %w", &apierror.Problem{Status: http.StatusNotFound}), expected: true}, + {name: "v8 other status", err: &upcloud.Problem{Status: http.StatusBadRequest}}, + {name: "v9 other status", err: &apierror.Problem{Status: http.StatusBadRequest}}, + {name: "plain error", err: fmt.Errorf("not found")}, + } { + t.Run(test.name, func(t *testing.T) { + assert.Equal(t, test.expected, IsNotFoundError(test.err)) + }) + } +} From e723c3c9e42b21faafcb727728bbc85ec6ae689a Mon Sep 17 00:00:00 2001 From: Francisco Serrano Date: Thu, 1 Oct 2026 15:47:26 +0300 Subject: [PATCH 4/7] fix: miscellaneous fixes --- go.mod | 2 +- go.sum | 2 ++ internal/commands/database/create.go | 40 ++++++++++++++++------- internal/commands/database/create_test.go | 35 +++++++++++++++++--- internal/commands/database/show_test.go | 6 +++- 5 files changed, 67 insertions(+), 18 deletions(-) diff --git a/go.mod b/go.mod index ed823c5e5..7ef0339e8 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ require ( github.com/UpCloudLtd/progress v1.2.1 github.com/UpCloudLtd/upcloud-go-api/credentials v0.1.1 github.com/UpCloudLtd/upcloud-go-api/v8 v8.40.0 - github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260929151619-56d6c5385c88 + github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260930115011-40a5b398d8a0 github.com/adrg/xdg v0.5.3 github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 github.com/google/uuid v1.6.0 diff --git a/go.sum b/go.sum index 98c0dcd1f..16553d31f 100644 --- a/go.sum +++ b/go.sum @@ -35,6 +35,8 @@ github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260917090650-3e1a69f90c36 h1:VC github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260917090650-3e1a69f90c36/go.mod h1:mHX52YNu+cWHzK7fNoT0g5TOzbVxgnfWZtJdWuhKHgs= github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260929151619-56d6c5385c88 h1:9L2gEK8MvxPkko0/ZYI8Ysx+F3fje/pWT044KQ6prbY= github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260929151619-56d6c5385c88/go.mod h1:mHX52YNu+cWHzK7fNoT0g5TOzbVxgnfWZtJdWuhKHgs= +github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260930115011-40a5b398d8a0 h1:Mos1nlJfDnBs0+pJnrP/X6Pkjs+Gh9oY1scK88maqmw= +github.com/UpCloudLtd/upcloud-go-api/v9 v9.0.0-20260930115011-40a5b398d8a0/go.mod h1:mHX52YNu+cWHzK7fNoT0g5TOzbVxgnfWZtJdWuhKHgs= github.com/adrg/xdg v0.5.3 h1:xRnxJXne7+oWDatRhR1JLnvuccuIeCoBu2rtuLqQB78= github.com/adrg/xdg v0.5.3/go.mod h1:nlTsY+NNiCBGCK2tpm09vRqfVzrc2fLmXGpBLF0zlTQ= github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= diff --git a/internal/commands/database/create.go b/internal/commands/database/create.go index ec8d37872..b81ff1aac 100644 --- a/internal/commands/database/create.go +++ b/internal/commands/database/create.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "slices" + "strconv" "strings" "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" @@ -74,7 +75,9 @@ type createParams struct { dbType string plan string planCompute string + planNodeCountValue string planNodeCount int + planStorageGiBValue string planStorageGiB int planBackups string maintenanceDow string @@ -290,7 +293,7 @@ func (s *createCommand) InitCommand() { For pg and mysql, select the plan by its components with --plan-compute, --plan-node-count, --plan-storage-gib, and --plan-backups. When any of these flags is given, the omitted ones use their defaults. Run "upctl database plans " to list the valid compute shapes, node counts, storage ranges, and backup tiers. --plan-storage-gib is the total storage per node, not additional storage. ---plan is deprecated for pg and mysql, but still supported, and it is required for other database types. Run "upctl database plans --show-legacy" to list plan names. --plan cannot be combined with the --plan-* flags. Without any plan flag, pg and mysql use the default of every --plan-* flag.`) +--plan is deprecated for pg and mysql, but still supported. Run "upctl database plans --show-legacy" to list their legacy plan names. --plan is required for other database types; run "upctl database plans " to list their plans. --plan cannot be combined with the --plan-* flags. Without any plan flag, pg and mysql use the default of every --plan-* flag.`) flags := &pflag.FlagSet{} s.params = createParams{} @@ -298,8 +301,8 @@ For pg and mysql, select the plan by its components with --plan-compute, --plan- flags.StringVar(&s.params.title, "title", "", "A short, informational description.") flags.StringVar(&s.params.plan, "plan", "", "Deprecated for pg and mysql, use the --plan-* flags instead. Plan name, required for database types other than pg and mysql.") flags.StringVar(&s.params.planCompute, "plan-compute", defaultPlanCompute, "Compute shape for pg and mysql, see the Compute shape column of \"upctl database plans \".") - flags.IntVar(&s.params.planNodeCount, "plan-node-count", defaultPlanNodeCount, "Number of nodes for pg and mysql.") - flags.IntVar(&s.params.planStorageGiB, "plan-storage-gib", defaultPlanStorageGiB, "Total storage per node in GiB for pg and mysql.") + flags.StringVar(&s.params.planNodeCountValue, "plan-node-count", strconv.Itoa(defaultPlanNodeCount), "Number of nodes for pg and mysql.") + flags.StringVar(&s.params.planStorageGiBValue, "plan-storage-gib", strconv.Itoa(defaultPlanStorageGiB), "Total storage per node in GiB for pg and mysql.") flags.StringVar(&s.params.planBackups, "plan-backups", defaultPlanBackups, "Backup tier for pg and mysql.") flags.StringVar(&s.params.zone, "zone", "", namedargs.ZoneDescription("database")) flags.StringVar(&s.params.dbType, "type", string(upcloudv9.DatabaseServiceTypeMysql), "Type of the database") @@ -317,9 +320,6 @@ For pg and mysql, select the plan by its components with --plan-compute, --plan- commands.Must(s.Cobra().MarkFlagRequired("title")) commands.Must(s.Cobra().MarkFlagRequired("zone")) commands.Must(s.Cobra().MarkFlagRequired("hostname-prefix")) - for _, flag := range planComponentFlags { - s.Cobra().MarkFlagsMutuallyExclusive("plan", flag) - } s.Cobra().MarkFlagsRequiredTogether("maintenance-dow", "maintenance-time") for _, flag := range append([]string{"hostname-prefix", "title", "plan", "maintenance-dow", "maintenance-time", "label", "network", "property"}, planComponentFlags...) { commands.Must(s.Cobra().RegisterFlagCompletionFunc(flag, cobra.NoFileCompletions)) @@ -336,27 +336,45 @@ func (s *createCommand) usesPlanComponents() (bool, error) { flags := s.Cobra().Flags() componentFlags := slices.ContainsFunc(planComponentFlags, flags.Changed) switch { + case flags.Changed("plan") && componentFlags: + return false, errors.New("--plan cannot be combined with component plan flags (--plan-compute, --plan-node-count, --plan-storage-gib, or --plan-backups)") case componentFlags && !supportsPlanComponents(s.params.dbType): return false, fmt.Errorf("the --plan-* flags are only supported for pg and mysql, use --plan for database type %q", s.params.dbType) - case componentFlags && s.params.planNodeCount < 1: - return false, fmt.Errorf("--plan-node-count must be a positive integer, got %d", s.params.planNodeCount) - case componentFlags && s.params.planStorageGiB < 1: - return false, fmt.Errorf("--plan-storage-gib must be a positive integer, got %d", s.params.planStorageGiB) case flags.Changed("plan"): return false, nil case supportsPlanComponents(s.params.dbType): + var err error + s.params.planNodeCount, err = positivePlanInteger("plan-node-count", s.params.planNodeCountValue) + if err != nil { + return false, err + } + s.params.planStorageGiB, err = positivePlanInteger("plan-storage-gib", s.params.planStorageGiBValue) + if err != nil { + return false, err + } return true, nil default: - return false, fmt.Errorf("--plan is required for database type %q, run \"upctl database plans %s --show-legacy\" to list available plans", s.params.dbType, s.params.dbType) + return false, fmt.Errorf("--plan is required for database type %q, run \"upctl database plans %s\" to list available plans", s.params.dbType, s.params.dbType) } } +func positivePlanInteger(flag, value string) (int, error) { + parsed, err := strconv.Atoi(value) + if err != nil || parsed < 1 { + return 0, fmt.Errorf("--%s must be a positive integer, got %q", flag, value) + } + return parsed, nil +} + // ExecuteWithoutArguments implements commands.NoArgumentCommand func (s *createCommand) ExecuteWithoutArguments(exec commands.Executor) (output.Output, error) { useComponents, err := s.usesPlanComponents() if err != nil { return nil, err } + if s.Cobra().Flags().Changed("plan") && supportsPlanComponents(s.params.dbType) { + _, _ = fmt.Fprintln(s.Cobra().ErrOrStderr(), "Deprecation Warning: --plan is deprecated for pg and mysql; use --plan-compute, --plan-node-count, --plan-storage-gib, and --plan-backups instead.") + } client, err := v9Client(exec) if err != nil { diff --git a/internal/commands/database/create_test.go b/internal/commands/database/create_test.go index 736fab923..8c533814e 100644 --- a/internal/commands/database/create_test.go +++ b/internal/commands/database/create_test.go @@ -152,6 +152,31 @@ func TestCreateCommand_Request(t *testing.T) { } } +func TestCreateCommand_LegacyPlanDeprecationWarning(t *testing.T) { + for _, test := range []struct { + name string + dbType string + wantWarning bool + }{ + {name: "pg", dbType: "pg", wantWarning: true}, + {name: "mysql", dbType: "mysql", wantWarning: true}, + {name: "opensearch", dbType: "opensearch", wantWarning: false}, + } { + t.Run(test.name, func(t *testing.T) { + api := newCreateAPI(t, fakeResponse{status: http.StatusCreated, body: createdDatabase}) + out, err := runCreate(t, api, config.New(), append(requiredCreateArgs, "--type", test.dbType, "--plan", "legacy-plan")...) + require.NoError(t, err) + + const warning = "Deprecation Warning: --plan is deprecated for pg and mysql" + if test.wantWarning { + assert.Contains(t, out, warning) + } else { + assert.NotContains(t, out, warning) + } + }) + } +} + func TestCreateCommand_Errors(t *testing.T) { for _, test := range []struct { name string @@ -163,25 +188,25 @@ func TestCreateCommand_Errors(t *testing.T) { { name: "plan and a component flag are mutually exclusive", args: append(requiredCreateArgs, "--type", "pg", "--plan", "2x2xCPU-4GB-100GB", "--plan-compute", "rdb.standard.2CPU-8GB"), - error: "if any flags in the group [plan plan-compute] are set none of the others can be; [plan plan-compute] were all set", + error: "--plan cannot be combined with component plan flags (--plan-compute, --plan-node-count, --plan-storage-gib, or --plan-backups)", beforeAPI: true, }, { name: "invalid numeric value", args: append(requiredCreateArgs, "--type", "pg", "--plan-node-count", "two"), - error: `invalid argument "two" for "--plan-node-count" flag`, + error: `--plan-node-count must be a positive integer, got "two"`, beforeAPI: true, }, { name: "non-positive node count", args: append(requiredCreateArgs, "--type", "pg", "--plan-node-count", "0"), - error: "--plan-node-count must be a positive integer, got 0", + error: `--plan-node-count must be a positive integer, got "0"`, beforeAPI: true, }, { name: "negative storage", args: append(requiredCreateArgs, "--type", "pg", "--plan-storage-gib", "-10"), - error: "--plan-storage-gib must be a positive integer, got -10", + error: `--plan-storage-gib must be a positive integer, got "-10"`, beforeAPI: true, }, { @@ -193,7 +218,7 @@ func TestCreateCommand_Errors(t *testing.T) { { name: "engine without component plans requires --plan", args: append(requiredCreateArgs, "--type", "valkey"), - error: `--plan is required for database type "valkey", run "upctl database plans valkey --show-legacy" to list available plans`, + error: `--plan is required for database type "valkey", run "upctl database plans valkey" to list available plans`, beforeAPI: true, }, { diff --git a/internal/commands/database/show_test.go b/internal/commands/database/show_test.go index 3a6e799df..fddab65f6 100644 --- a/internal/commands/database/show_test.go +++ b/internal/commands/database/show_test.go @@ -65,7 +65,11 @@ func TestShowCommand(t *testing.T) { "plan": "rdb.standard.2x-2CPU-8GB-120GB-regular", "termination_protection": true, "plan_components": {"compute": {"name": "rdb.standard.2CPU-8GB", "node_count": 2, "cpu": 2, "memory_gb": 8}, "storage": {"total_gib": 120}, "backups": {"name": "regular"}}, "metadata": {"pg_version": "16"}, - "maintenance": {"dow": "sunday", "time": "05:00:00"}, + "maintenance": { + "dow": "sunday", + "time": "05:00:00", + "pending_updates": [{"deadline": "", "description": "platform update", "start_after": "2026-09-30T10:00:00Z", "start_at": ""}] + }, "service_uri_params": {"dbname": "defaultdb", "host": "my-pg.example.com", "port": 11550, "user": "upadmin"}, "labels": [{"key": "env", "value": "dev"}], "node_states": [{"name": "my-pg-1", "role": "master", "state": "running"}], From 00ef92004b0b20723da54e3e3db735e78eaf2d3e Mon Sep 17 00:00:00 2001 From: Francisco Serrano Date: Thu, 1 Oct 2026 16:15:55 +0300 Subject: [PATCH 5/7] fix(database): preserve machine-readable output --- CHANGELOG.md | 2 +- internal/commands/database/create.go | 6 +++- internal/commands/database/create_test.go | 3 +- internal/commands/database/list.go | 6 +++- internal/commands/database/list_test.go | 8 ++--- internal/commands/database/show.go | 6 +++- internal/commands/database/show_test.go | 11 +++--- internal/commands/database/v9.go | 42 +++++++++++++++++++++++ 8 files changed, 70 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40977f760..0ba81efa1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- `database create`, `database list`, `database show`, and `database delete` use the v9 SDK. The JSON and YAML output of `database create`, `database list`, and `database show` follows the v9 API response shape. +- `database create`, `database list`, `database show`, and `database delete` use the v9 SDK. Their existing JSON and YAML output shape is preserved. - `database show` displays the plan components of componentised plans. - `database create` without a plan flag now creates PostgreSQL and MySQL databases with the `--plan-*` defaults instead of the `2x2xCPU-4GB-100GB` plan: `rdb.standard.2CPU-8GB` compute with 8 GB memory per node instead of 4 GB, 2 nodes, 100 GiB storage per node, and the `regular` backup tier instead of the legacy backup retention of 8 days for MySQL and 15 days for PostgreSQL. - `database create`: `--plan` is deprecated for PostgreSQL and MySQL, and it cannot be combined with the `--plan-*` flags. `--plan` no longer has a default, and it is required for database types other than PostgreSQL and MySQL. diff --git a/internal/commands/database/create.go b/internal/commands/database/create.go index b81ff1aac..7cf7539dc 100644 --- a/internal/commands/database/create.go +++ b/internal/commands/database/create.go @@ -417,6 +417,10 @@ func (s *createCommand) ExecuteWithoutArguments(exec commands.Executor) (output. return commands.HandleError(exec, msg, apierror.FromResponse(res.StatusCode(), res.Body)) } db := res.JSON201 + legacyOutput, err := legacyDatabaseOutput(db) + if err != nil { + return commands.HandleError(exec, msg, err) + } if db.Uuid == nil { return commands.HandleError(exec, msg, errors.New("the API response did not include the database UUID")) } @@ -428,7 +432,7 @@ func (s *createCommand) ExecuteWithoutArguments(exec commands.Executor) (output. exec.PushProgressSuccess(msg) } - return output.MarshaledWithHumanDetails{Value: db, Details: []output.DetailRow{ + return output.MarshaledWithHumanDetails{Value: legacyOutput, Details: []output.DetailRow{ {Title: "UUID", Value: id, Colour: ui.DefaultUUUIDColours}, }}, nil } diff --git a/internal/commands/database/create_test.go b/internal/commands/database/create_test.go index 8c533814e..adffebf91 100644 --- a/internal/commands/database/create_test.go +++ b/internal/commands/database/create_test.go @@ -32,7 +32,7 @@ const planCatalog = `{"service_types": [ ]} ]}` -const createdDatabase = `{"uuid": "` + createdDatabaseUUID + `", "title": "db-test", "type": "pg", "state": "rebuilding", "plan": "rdb.standard.2x-2CPU-8GB-100GB-regular"}` +const createdDatabase = `{"uuid": "` + createdDatabaseUUID + `", "title": "db-test", "type": "pg", "state": "rebuilding", "plan": "rdb.standard.2x-2CPU-8GB-100GB-regular", "plan_components": {"compute": {"name": "rdb.standard.2CPU-8GB"}}}` // serviceType uses a list type for version, as the live API does. const serviceType = `{"name": "pg", "properties": { @@ -304,6 +304,7 @@ func TestCreateCommand_Output(t *testing.T) { require.NoError(t, json.Unmarshal([]byte(out), &body)) assert.Equal(t, createdDatabaseUUID, body["uuid"]) assert.Equal(t, "rdb.standard.2x-2CPU-8GB-100GB-regular", body["plan"]) + assert.NotContains(t, body, "plan_components") } func TestCreateCommand_Wait(t *testing.T) { diff --git a/internal/commands/database/list.go b/internal/commands/database/list.go index e56473898..3b68163b2 100644 --- a/internal/commands/database/list.go +++ b/internal/commands/database/list.go @@ -48,6 +48,10 @@ func (s *listCommand) ExecuteWithoutArguments(exec commands.Executor) (output.Ou return nil, apierror.FromResponse(res.StatusCode(), res.Body) } databases := *res.JSON200 + legacyOutput, err := legacyDatabaseListOutput(databases) + if err != nil { + return nil, err + } rows := []output.TableRow{} for _, db := range databases { @@ -67,7 +71,7 @@ func (s *listCommand) ExecuteWithoutArguments(exec commands.Executor) (output.Ou } return output.MarshaledWithHumanOutput{ - Value: databases, + Value: legacyOutput, Output: output.Table{ Columns: []output.TableColumn{ {Key: "uuid", Header: "UUID", Colour: ui.DefaultUUUIDColours}, diff --git a/internal/commands/database/list_test.go b/internal/commands/database/list_test.go index 584542829..06ad84a58 100644 --- a/internal/commands/database/list_test.go +++ b/internal/commands/database/list_test.go @@ -65,7 +65,7 @@ func TestDatabaseListTitleFallback(t *testing.T) { } } -func TestDatabaseListMachineReadableOutputUsesV9Response(t *testing.T) { +func TestDatabaseListMachineReadableOutputPreservesLegacyResponse(t *testing.T) { const id = "091f1afe-4ddd-4d43-afad-6aa3069cc7fe" databases := `[{"uuid":"` + id + `","title":"service-name","type":"mysql","plan_components":{"compute":{"name":"rdb.standard.2CPU-8GB","node_count":2}}}]` @@ -78,14 +78,14 @@ func TestDatabaseListMachineReadableOutputUsesV9Response(t *testing.T) { out, err := mockexecute.MockExecuteWithV9(command, &smock.Service{}, api.client, conf) require.NoError(t, err) - assert.Contains(t, out, "plan_components") - assert.Contains(t, out, "rdb.standard.2CPU-8GB") + assert.NotContains(t, out, "plan_components") + assert.NotContains(t, out, "rdb.standard.2CPU-8GB") if outputFormat == config.ValueOutputJSON { var got []map[string]any require.NoError(t, json.Unmarshal([]byte(out), &got)) require.Len(t, got, 1) assert.Equal(t, id, got[0]["uuid"]) - assert.Contains(t, got[0], "plan_components") + assert.NotContains(t, got[0], "plan_components") } }) } diff --git a/internal/commands/database/show.go b/internal/commands/database/show.go index f8b33cd95..18c1fd35e 100644 --- a/internal/commands/database/show.go +++ b/internal/commands/database/show.go @@ -50,6 +50,10 @@ func (s *showCommand) Execute(exec commands.Executor, uuidStr string) (output.Ou return nil, apierror.FromResponse(res.StatusCode(), res.Body) } db := res.JSON200 + legacyOutput, err := legacyDatabaseOutput(db) + if err != nil { + return nil, err + } dbType := deref(db.Type) nodeRows := []output.TableRow{} @@ -136,7 +140,7 @@ func (s *showCommand) Execute(exec commands.Executor, uuidStr string) (output.Ou // For JSON and YAML output, passthrough API response return output.MarshaledWithHumanOutput{ - Value: db, + Value: legacyOutput, Output: output.Combined{ output.CombinedSection{ Contents: output.Details{ diff --git a/internal/commands/database/show_test.go b/internal/commands/database/show_test.go index fddab65f6..bd284e088 100644 --- a/internal/commands/database/show_test.go +++ b/internal/commands/database/show_test.go @@ -135,9 +135,9 @@ func TestShowCommand_MySQL(t *testing.T) { assert.Regexp(t, `Version:\s+8`, out) } -func TestShowCommand_MachineReadableOutputUsesV9Response(t *testing.T) { +func TestShowCommand_MachineReadableOutputPreservesLegacyResponse(t *testing.T) { id := shownDatabaseUUID - response := `{"uuid":"` + id + `","title":"my-pg","type":"pg","plan_components":{"compute":{"name":"rdb.standard.2CPU-8GB","node_count":2}}}` + response := `{"uuid":"` + id + `","title":"my-pg","type":"pg","service_uri_params":{"port":11550},"plan_components":{"compute":{"name":"rdb.standard.2CPU-8GB","node_count":2}}}` for _, outputFormat := range []string{config.ValueOutputJSON, config.ValueOutputYAML} { t.Run(outputFormat, func(t *testing.T) { @@ -149,13 +149,14 @@ func TestShowCommand_MachineReadableOutputUsesV9Response(t *testing.T) { out, err := mockexecute.MockExecuteWithV9(c, &smock.Service{}, api.client, conf) require.NoError(t, err) - assert.Contains(t, out, "plan_components") - assert.Contains(t, out, "rdb.standard.2CPU-8GB") + assert.NotContains(t, out, "plan_components") + assert.NotContains(t, out, "rdb.standard.2CPU-8GB") if outputFormat == config.ValueOutputJSON { var got map[string]any require.NoError(t, json.Unmarshal([]byte(out), &got)) assert.Equal(t, id, got["uuid"]) - assert.Contains(t, got, "plan_components") + assert.NotContains(t, got, "plan_components") + assert.Equal(t, "11550", got["service_uri_params"].(map[string]any)["port"]) } }) } diff --git a/internal/commands/database/v9.go b/internal/commands/database/v9.go index 58aaadb86..b71055069 100644 --- a/internal/commands/database/v9.go +++ b/internal/commands/database/v9.go @@ -14,6 +14,7 @@ import ( "github.com/UpCloudLtd/upcloud-cli/v3/internal/apierror" "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" + upcloudv8 "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud" upcloudv9 "github.com/UpCloudLtd/upcloud-go-api/v9/pkg/upcloud" "github.com/google/uuid" ) @@ -23,6 +24,47 @@ const ( databaseStateError = "error" ) +// legacyDatabaseOutput preserves the database JSON/YAML contract while CRUD API calls use v9. +func legacyDatabaseOutput(db *upcloudv9.DatabaseServiceInformationResponse) (*upcloudv8.ManagedDatabase, error) { + body, err := json.Marshal(db) + if err != nil { + return nil, fmt.Errorf("cannot marshal v9 database response: %w", err) + } + var normalized map[string]any + if err := json.Unmarshal(body, &normalized); err != nil { + return nil, fmt.Errorf("cannot normalize v9 database response: %w", err) + } + if params, ok := normalized["service_uri_params"].(map[string]any); ok { + for key, value := range params { + if value != nil { + params[key] = fmt.Sprint(value) + } + } + } + body, err = json.Marshal(normalized) + if err != nil { + return nil, fmt.Errorf("cannot marshal normalized database response: %w", err) + } + + legacy := &upcloudv8.ManagedDatabase{} + if err := json.Unmarshal(body, legacy); err != nil { + return nil, fmt.Errorf("cannot convert v9 database response to legacy output: %w", err) + } + return legacy, nil +} + +func legacyDatabaseListOutput(databases []upcloudv9.DatabaseServiceInformationResponse) ([]upcloudv8.ManagedDatabase, error) { + legacy := make([]upcloudv8.ManagedDatabase, 0, len(databases)) + for i := range databases { + db, err := legacyDatabaseOutput(&databases[i]) + if err != nil { + return nil, err + } + legacy = append(legacy, *db) + } + return legacy, nil +} + // databasePollInterval matches the v8 SDK wait helpers. var databasePollInterval = 5 * time.Second From ad3841906d36a85bbf4c83d62829a6b12597b22a Mon Sep 17 00:00:00 2001 From: Francisco Serrano Date: Fri, 2 Oct 2026 11:15:50 +0300 Subject: [PATCH 6/7] fix: check availabiilty zone --- internal/commands/database/create.go | 32 ++++++++++++++++++----- internal/commands/database/create_test.go | 30 ++++++++++++++++++++- 2 files changed, 54 insertions(+), 8 deletions(-) diff --git a/internal/commands/database/create.go b/internal/commands/database/create.go index 7cf7539dc..20ecffc5a 100644 --- a/internal/commands/database/create.go +++ b/internal/commands/database/create.go @@ -152,6 +152,20 @@ func (p *createParams) request(properties map[string]propertySchema) (upcloudv9. return req, nil } +// validateZone checks that the database type is offered in the requested zone. +func (p *createParams) validateZone(catalog *upcloudv9.DatabasePlansResponse) error { + for _, serviceType := range catalog.ServiceTypes { + if string(serviceType.Type) != p.dbType { + continue + } + if !slices.Contains(serviceType.Zones, p.zone) { + return fmt.Errorf("--zone %q is not available for database type %q, valid zones are %s", p.zone, p.dbType, strings.Join(serviceType.Zones, ", ")) + } + return nil + } + return fmt.Errorf("database type %q is not available in the plan catalog", p.dbType) +} + // applyPlanComponents validates the plan components against the plan catalog and sets them on the request. func (p *createParams) applyPlanComponents(catalog *upcloudv9.DatabasePlansResponse, changed func(string) bool, req *upcloudv9.DatabaseServiceCreateOpenAPI) error { hint := fmt.Sprintf("run \"upctl database plans %s\" to list valid values", p.dbType) @@ -394,14 +408,18 @@ func (s *createCommand) ExecuteWithoutArguments(exec commands.Executor) (output. return nil, err } + plans, err := client.ListDatabasePlansWithResponse(exec.Context()) + if err != nil { + return commands.HandleError(exec, msg, err) + } + if plans.JSON200 == nil { + return commands.HandleError(exec, msg, apierror.FromResponse(plans.StatusCode(), plans.Body)) + } + if err := s.params.validateZone(plans.JSON200); err != nil { + return commands.HandleError(exec, msg, err) + } + if useComponents { - plans, err := client.ListDatabasePlansWithResponse(exec.Context()) - if err != nil { - return commands.HandleError(exec, msg, err) - } - if plans.JSON200 == nil { - return commands.HandleError(exec, msg, apierror.FromResponse(plans.StatusCode(), plans.Body)) - } if err := s.params.applyPlanComponents(plans.JSON200, s.Cobra().Flags().Changed, &req); err != nil { return commands.HandleError(exec, msg, err) } diff --git a/internal/commands/database/create_test.go b/internal/commands/database/create_test.go index adffebf91..96acef06c 100644 --- a/internal/commands/database/create_test.go +++ b/internal/commands/database/create_test.go @@ -29,7 +29,9 @@ const planCatalog = `{"service_types": [ {"compute": "rdb.standard.2CPU-8GB", "family": "standard", "cpu": 2, "memory_gb": 8, "dynamic_storage_supported": true, "node_counts": [1, 2, 3], "backups": ["regular", "extended"], "storage": {"dynamic_max_multiplier": 4, "step_gib": 10, "total_cap_gib": 10240, "options": [{"base_gib": 80, "max_gib": 400}]}} - ]} + ]}, + {"type": "opensearch", "componentised": false, "zones": ["fi-hel1"], "compute_shapes": []}, + {"type": "valkey", "componentised": false, "zones": ["fi-hel1"], "compute_shapes": []} ]}` const createdDatabase = `{"uuid": "` + createdDatabaseUUID + `", "title": "db-test", "type": "pg", "state": "rebuilding", "plan": "rdb.standard.2x-2CPU-8GB-100GB-regular", "plan_components": {"compute": {"name": "rdb.standard.2CPU-8GB"}}}` @@ -290,6 +292,32 @@ func TestCreateCommand_Errors(t *testing.T) { } } +func TestCreateCommand_RejectsUnavailableZoneBeforeCreate(t *testing.T) { + for _, test := range []struct { + name string + args []string + }{ + { + name: "component plan", + args: []string{"--type", "pg", "--plan-storage-gib", "100"}, + }, + { + name: "named plan", + args: []string{"--type", "opensearch", "--plan", "1x2xCPU-4GB-80GB-1D"}, + }, + } { + t.Run(test.name, func(t *testing.T) { + api := newCreateAPI(t, fakeResponse{status: http.StatusCreated, body: createdDatabase}) + args := []string{"--title", "db-test", "--zone", "de-fra1", "--hostname-prefix", "testdb"} + _, err := runCreate(t, api, config.New(), append(args, test.args...)...) + + require.EqualError(t, err, `--zone "de-fra1" is not available for database type "`+test.args[1]+`", valid zones are fi-hel1`) + assert.Empty(t, api.requestsTo(http.MethodPost, "/1.3/database")) + require.Len(t, api.requestsTo(http.MethodGet, "/1.3/database/plans"), 1) + }) + } +} + func TestCreateCommand_Output(t *testing.T) { api := newCreateAPI(t, fakeResponse{status: http.StatusCreated, body: createdDatabase}) out, err := runCreate(t, api, config.New(), requiredCreateArgs...) From 2eaba979693905b18ea11a122e39f5a8422a87ad Mon Sep 17 00:00:00 2001 From: Francisco Serrano Date: Mon, 5 Oct 2026 12:18:59 +0300 Subject: [PATCH 7/7] fix: proper validation of legacy plans --- internal/commands/database/create.go | 54 ++++++++--- internal/commands/database/create_test.go | 112 +++++++++++++++++++--- internal/commands/database/v9.go | 17 ++-- 3 files changed, 148 insertions(+), 35 deletions(-) diff --git a/internal/commands/database/create.go b/internal/commands/database/create.go index 20ecffc5a..cc8d408e1 100644 --- a/internal/commands/database/create.go +++ b/internal/commands/database/create.go @@ -166,6 +166,34 @@ func (p *createParams) validateZone(catalog *upcloudv9.DatabasePlansResponse) er return fmt.Errorf("database type %q is not available in the plan catalog", p.dbType) } +func (p *createParams) validateLegacyPlan(plans []upcloudv9.DatabaseServicePlanResponse) error { + for _, plan := range plans { + if plan.Plan == nil || *plan.Plan != p.plan { + continue + } + if plan.Zones == nil || plan.Zones.Zone == nil { + return fmt.Errorf("availability zones are not available for database plan %q", p.plan) + } + + zones := make([]string, 0, len(*plan.Zones.Zone)) + for _, zone := range *plan.Zones.Zone { + if zone.Name != nil { + zones = append(zones, *zone.Name) + } + } + if !slices.Contains(zones, p.zone) { + return fmt.Errorf("--zone %q is not available for database plan %q, valid zones are %s", p.zone, p.plan, strings.Join(zones, ", ")) + } + return nil + } + + hint := fmt.Sprintf("run \"upctl database plans %s\" to list valid values", p.dbType) + if supportsPlanComponents(p.dbType) { + hint = fmt.Sprintf("run \"upctl database plans %s --show-legacy\" to list legacy plans", p.dbType) + } + return fmt.Errorf("--plan %q is not available for database type %q, %s", p.plan, p.dbType, hint) +} + // applyPlanComponents validates the plan components against the plan catalog and sets them on the request. func (p *createParams) applyPlanComponents(catalog *upcloudv9.DatabasePlansResponse, changed func(string) bool, req *upcloudv9.DatabaseServiceCreateOpenAPI) error { hint := fmt.Sprintf("run \"upctl database plans %s\" to list valid values", p.dbType) @@ -398,7 +426,7 @@ func (s *createCommand) ExecuteWithoutArguments(exec commands.Executor) (output. msg := fmt.Sprintf("Creating database %v", s.params.title) exec.PushProgressStarted(msg) - properties, err := getServiceTypeProperties(exec.Context(), client, s.params.dbType) + properties, legacyPlans, err := getServiceTypeDetails(exec.Context(), client, s.params.dbType) if err != nil { return commands.HandleError(exec, msg, err) } @@ -408,22 +436,24 @@ func (s *createCommand) ExecuteWithoutArguments(exec commands.Executor) (output. return nil, err } - plans, err := client.ListDatabasePlansWithResponse(exec.Context()) - if err != nil { - return commands.HandleError(exec, msg, err) - } - if plans.JSON200 == nil { - return commands.HandleError(exec, msg, apierror.FromResponse(plans.StatusCode(), plans.Body)) - } - if err := s.params.validateZone(plans.JSON200); err != nil { - return commands.HandleError(exec, msg, err) - } - if useComponents { + plans, err := client.ListDatabasePlansWithResponse(exec.Context()) + if err != nil { + return commands.HandleError(exec, msg, err) + } + if plans.JSON200 == nil { + return commands.HandleError(exec, msg, apierror.FromResponse(plans.StatusCode(), plans.Body)) + } + if err := s.params.validateZone(plans.JSON200); err != nil { + return commands.HandleError(exec, msg, err) + } if err := s.params.applyPlanComponents(plans.JSON200, s.Cobra().Flags().Changed, &req); err != nil { return commands.HandleError(exec, msg, err) } } else { + if err := s.params.validateLegacyPlan(legacyPlans); err != nil { + return commands.HandleError(exec, msg, err) + } req.Plan = &s.params.plan } diff --git a/internal/commands/database/create_test.go b/internal/commands/database/create_test.go index 96acef06c..1f53ea4a7 100644 --- a/internal/commands/database/create_test.go +++ b/internal/commands/database/create_test.go @@ -36,12 +36,35 @@ const planCatalog = `{"service_types": [ const createdDatabase = `{"uuid": "` + createdDatabaseUUID + `", "title": "db-test", "type": "pg", "state": "rebuilding", "plan": "rdb.standard.2x-2CPU-8GB-100GB-regular", "plan_components": {"compute": {"name": "rdb.standard.2CPU-8GB"}}}` -// serviceType uses a list type for version, as the live API does. -const serviceType = `{"name": "pg", "properties": { - "version": {"type": ["string", "null"], "title": "Version"}, - "numeric_string": {"type": "string", "title": "Numeric string"}, - "max_connections": {"type": "integer", "title": "Max connections"} -}}` +// serviceTypeResponse uses a list type for version, as the live API does. +func serviceTypeResponse(dbType string) string { + legacyPlans := map[string][]string{ + "mysql": {"legacy-plan", "4x4xCPU-8GB-200GB"}, + "pg": {"legacy-plan", "4x4xCPU-8GB-200GB"}, + "opensearch": {"legacy-plan", "1x2xCPU-4GB-80GB-1D"}, + "valkey": {"legacy-plan", "1x2xCPU-4GB-80GB-1D"}, + } + plans := make([]map[string]any, 0, len(legacyPlans[dbType])) + for _, name := range legacyPlans[dbType] { + plans = append(plans, map[string]any{ + "plan": name, + "zones": map[string]any{"zone": []map[string]string{{"name": "fi-hel1"}}}, + }) + } + body, err := json.Marshal(map[string]any{ + "name": dbType, + "properties": map[string]any{ + "version": map[string]any{"type": []string{"string", "null"}, "title": "Version"}, + "numeric_string": map[string]any{"type": "string", "title": "Numeric string"}, + "max_connections": map[string]any{"type": "integer", "title": "Max connections"}, + }, + "service_plans": plans, + }) + if err != nil { + panic(err) + } + return string(body) +} func newCreateAPI(t *testing.T, create fakeResponse) *fakeAPI { responses := map[string]fakeResponse{ @@ -53,7 +76,7 @@ func newCreateAPI(t *testing.T, create fakeResponse) *fakeAPI { }}, } for _, dbType := range []string{"mysql", "pg", "opensearch", "valkey"} { - responses["GET /1.3/database/service-types/"+dbType] = fakeResponse{status: http.StatusOK, body: serviceType} + responses["GET /1.3/database/service-types/"+dbType] = fakeResponse{status: http.StatusOK, body: serviceTypeResponse(dbType)} } return newFakeAPI(t, responses) } @@ -87,6 +110,11 @@ func TestCreateCommand_Request(t *testing.T) { "labels": [{"key": "env", "value": "test"}, {"key": "app", "value": "database"}], "termination_protection": true, "properties": {"version": "13", "max_connections": 200}}`, }, + { + name: "mysql legacy plan remains supported", + args: []string{"--type", "mysql", "--plan", "4x4xCPU-8GB-200GB"}, + expected: `{"hostname_prefix": "testdb", "plan": "4x4xCPU-8GB-200GB", "title": "db-test", "type": "mysql", "zone": "fi-hel1"}`, + }, { name: "opensearch with typed properties", args: []string{ @@ -100,6 +128,11 @@ func TestCreateCommand_Request(t *testing.T) { expected: `{"hostname_prefix": "testdb", "plan": "1x2xCPU-4GB-80GB-1D", "title": "db-test", "type": "opensearch", "zone": "fi-hel1", "properties": {"saml": {"enabled": true}, "openid": {"client_id": "test_client_id"}, "ism_enabled": true, "custom_domain": "custom.upcloud.com", "numeric_string": "123"}}`, }, + { + name: "valkey uses its legacy plan catalog", + args: []string{"--type", "valkey", "--plan", "1x2xCPU-4GB-80GB-1D"}, + expected: `{"hostname_prefix": "testdb", "plan": "1x2xCPU-4GB-80GB-1D", "title": "db-test", "type": "valkey", "zone": "fi-hel1"}`, + }, { name: "maintenance and networks", args: []string{ @@ -149,11 +182,24 @@ func TestCreateCommand_Request(t *testing.T) { require.NoError(t, json.Unmarshal(creates[0].Body, &body)) assert.NotContains(t, body, "plan", "component selection must not send an implicit plan") assert.NotContains(t, body, "additional_disk_space_gib", "plan_storage_gib is exclusive with additional_disk_space_gib") + require.Len(t, api.requestsTo(http.MethodGet, "/1.3/database/plans"), 1) + } else { + assert.Empty(t, api.requestsTo(http.MethodGet, "/1.3/database/plans"), "legacy plan validation must not depend on the component plan catalog") } + assert.Len(t, api.requestsTo(http.MethodGet, "/1.3/database/service-types/"+databaseTypeFromArgs(test.args)), 1) }) } } +func databaseTypeFromArgs(args []string) string { + for i, arg := range args { + if arg == "--type" && i+1 < len(args) { + return args[i+1] + } + } + return "mysql" +} + func TestCreateCommand_LegacyPlanDeprecationWarning(t *testing.T) { for _, test := range []struct { name string @@ -294,16 +340,21 @@ func TestCreateCommand_Errors(t *testing.T) { func TestCreateCommand_RejectsUnavailableZoneBeforeCreate(t *testing.T) { for _, test := range []struct { - name string - args []string + name string + args []string + error string + componentPlan bool }{ { - name: "component plan", - args: []string{"--type", "pg", "--plan-storage-gib", "100"}, + name: "component plan", + args: []string{"--type", "pg", "--plan-storage-gib", "100"}, + error: `--zone "de-fra1" is not available for database type "pg", valid zones are fi-hel1`, + componentPlan: true, }, { - name: "named plan", - args: []string{"--type", "opensearch", "--plan", "1x2xCPU-4GB-80GB-1D"}, + name: "named plan", + args: []string{"--type", "opensearch", "--plan", "1x2xCPU-4GB-80GB-1D"}, + error: `--zone "de-fra1" is not available for database plan "1x2xCPU-4GB-80GB-1D", valid zones are fi-hel1`, }, } { t.Run(test.name, func(t *testing.T) { @@ -311,9 +362,40 @@ func TestCreateCommand_RejectsUnavailableZoneBeforeCreate(t *testing.T) { args := []string{"--title", "db-test", "--zone", "de-fra1", "--hostname-prefix", "testdb"} _, err := runCreate(t, api, config.New(), append(args, test.args...)...) - require.EqualError(t, err, `--zone "de-fra1" is not available for database type "`+test.args[1]+`", valid zones are fi-hel1`) + require.EqualError(t, err, test.error) + assert.Empty(t, api.requestsTo(http.MethodPost, "/1.3/database")) + if test.componentPlan { + require.Len(t, api.requestsTo(http.MethodGet, "/1.3/database/plans"), 1) + } else { + assert.Empty(t, api.requestsTo(http.MethodGet, "/1.3/database/plans")) + } + }) + } +} + +func TestCreateCommand_RejectsUnknownLegacyPlanBeforeCreate(t *testing.T) { + for _, test := range []struct { + name string + args []string + error string + }{ + { + name: "deprecated postgres plan", + args: []string{"--type", "pg", "--plan", "unknown-plan"}, + error: `--plan "unknown-plan" is not available for database type "pg", run "upctl database plans pg --show-legacy" to list legacy plans`, + }, + { + name: "legacy-only engine plan", + args: []string{"--type", "opensearch", "--plan", "unknown-plan"}, + error: `--plan "unknown-plan" is not available for database type "opensearch", run "upctl database plans opensearch" to list valid values`, + }, + } { + t.Run(test.name, func(t *testing.T) { + api := newCreateAPI(t, fakeResponse{status: http.StatusCreated, body: createdDatabase}) + _, err := runCreate(t, api, config.New(), append(requiredCreateArgs, test.args...)...) + require.EqualError(t, err, test.error) assert.Empty(t, api.requestsTo(http.MethodPost, "/1.3/database")) - require.Len(t, api.requestsTo(http.MethodGet, "/1.3/database/plans"), 1) + assert.Empty(t, api.requestsTo(http.MethodGet, "/1.3/database/plans")) }) } } diff --git a/internal/commands/database/v9.go b/internal/commands/database/v9.go index b71055069..70a33045e 100644 --- a/internal/commands/database/v9.go +++ b/internal/commands/database/v9.go @@ -128,29 +128,30 @@ func (p propertySchema) allowsString() bool { return false } -// getServiceTypeProperties decodes the response itself, as the generated v9 model cannot decode list-valued property types. -func getServiceTypeProperties(ctx context.Context, client *upcloudv9.ClientWithResponses, dbType string) (map[string]propertySchema, error) { +// getServiceTypeDetails decodes the response itself because generated property schemas cannot decode list-valued types. +func getServiceTypeDetails(ctx context.Context, client *upcloudv9.ClientWithResponses, dbType string) (map[string]propertySchema, []upcloudv9.DatabaseServicePlanResponse, error) { res, err := client.GetDatabaseType(ctx, upcloudv9.GetDatabaseTypeServiceTypeName(dbType)) if err != nil { - return nil, err + return nil, nil, err } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { - return nil, err + return nil, nil, err } if res.StatusCode != http.StatusOK { - return nil, apierror.FromResponse(res.StatusCode, body) + return nil, nil, apierror.FromResponse(res.StatusCode, body) } var serviceType struct { - Properties map[string]propertySchema `json:"properties"` + Properties map[string]propertySchema `json:"properties"` + ServicePlans []upcloudv9.DatabaseServicePlanResponse `json:"service_plans"` } if err := json.Unmarshal(body, &serviceType); err != nil { - return nil, fmt.Errorf("cannot parse database type %s: %w", dbType, err) + return nil, nil, fmt.Errorf("cannot parse database type %s: %w", dbType, err) } - return serviceType.Properties, nil + return serviceType.Properties, serviceType.ServicePlans, nil } // waitForDatabaseState polls like the v8 SDK, retrying up to three consecutive server errors.