diff --git a/.gitignore b/.gitignore index d30036c0..9e6d7169 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,20 @@ -.idea/ -*.iml -*.example +# Temporary +.*.swp +.idea +/.vs +.DS_Store +core.* +debug +debug.test +.vscode -uhost_example \ No newline at end of file +# Executable +bin/ +*.dll +*.exe + +# Build +coverage.out + +# Test Data +# autotest/set_* \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..e69de29b diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 2bf1c3aa..00000000 --- a/Dockerfile +++ /dev/null @@ -1,8 +0,0 @@ -FROM golang:1.8.3-alpine - -ENV GOPATH /go -ENV USER root - -WORKDIR /go/src/github.com/ucloud/ucloud-sdk-go - -ADD . /go/src/github.com/ucloud/ucloud-sdk-go diff --git a/Gopkg.lock b/Gopkg.lock new file mode 100644 index 00000000..29f26060 --- /dev/null +++ b/Gopkg.lock @@ -0,0 +1,39 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + name = "github.com/Sirupsen/logrus" + packages = ["."] + revision = "418b41d23a1bf978c06faea5313ba194650ac088" + version = "v0.8.7" + +[[projects]] + name = "github.com/davecgh/go-spew" + packages = ["spew"] + revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" + version = "v1.1.1" + +[[projects]] + name = "github.com/pkg/errors" + packages = ["."] + revision = "645ef00459ed84a119197bfb8d8205042c6df63d" + version = "v0.8.0" + +[[projects]] + name = "github.com/pmezard/go-difflib" + packages = ["difflib"] + revision = "792786c7400a136282c1664665ae0a8db921c6c2" + version = "v1.0.0" + +[[projects]] + name = "github.com/stretchr/testify" + packages = ["assert"] + revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686" + version = "v1.2.2" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "10f5ab6a4a29bc3f72240bd952045886b9ec11934d267fdb794656ff5c79f21f" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml new file mode 100644 index 00000000..24f0f175 --- /dev/null +++ b/Gopkg.toml @@ -0,0 +1,30 @@ +# Gopkg.toml example +# +# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" +# +# [prune] +# non-go = false +# go-tests = true +# unused-packages = true + + +[prune] + go-tests = true + unused-packages = true diff --git a/Makefile b/Makefile index fbc4b395..8be8f571 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,37 @@ -.PHONY: test example +GOFMT_FILES?=$$(find . -name '*.go' |grep -v vendor) -default: test - -test: - script/test +.PHONY: help +help: + @echo "fmt re-format source codes." + @echo "build build binary from source code as './bin/ucloud-cli'." + @echo "test run unit test cases." + @echo "test-acc run acc test cases." + @echo "test-cov run unit test cases with coverage reporting." -example: - script/example \ No newline at end of file +.PHONY: fmt +fmt: + gofmt -w $(GOFMT_FILES) + +.PHONY: fmtcheck +fmtcheck: + @sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" + +.PHONY: vet +vet: + go vet ./... + +.PHONY: test +test: fmtcheck vet + go test -v ./ucloud/... --parallel=4 + +.PHONY: test-acc +test-acc: fmtcheck vet + go test -v ./tests/... --parallel=32 + +.PHONY: test-cov +test-cov: fmtcheck vet + go test -cover -coverprofile=coverage.out ./... --parallel=32 + +.PHONY: cyclo +cyclo: + gocyclo -over 10 sdk/ service/ private/cli/ diff --git a/README.md b/README.md index 9756fed2..cacf5bf0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,28 @@ -# goucloud -golang sdk for ucloud api +# UCloud Golang SDK + +UCloud Golang SDK is a toolkit for developer to create custom infrastructure via ucloud open api. + +## Install + +### via source + +```go +go get github.com/ucloud/ucloud-sdk-go +``` + +### via dep + +``` +dep add github.com/ucloud/ucloud-sdk-go +``` + +## Useful Docs + +- [Configure Document](./docs/Configure.md) +- [Usage Document](./docs/Usage.md) +- *Retry Policy (wait for writing)* + +## Feedback && Contributing + +- [Issue](https://github.com/ucloud/ucloud-sdk-go/issues) +- [Pull Request](https://github.com/ucloud/ucloud-sdk-go/pulls) diff --git a/docs/Configure.md b/docs/Configure.md new file mode 100644 index 00000000..af0c1d60 --- /dev/null +++ b/docs/Configure.md @@ -0,0 +1,68 @@ +## Configure SDK + +### Client Config + +client config can control many common behaviors of sdk, it is required for any client. + +#### Common Request Fields + +To set common region and project id for any request, you can also overwrite it by request. + +```go +cfg := ucloud.NewConfig() + +cfg.Region = "cn-bj2" +cfg.ProjectId = "xxx" +``` + +#### Auto Retry + +To enable auto-retry for any request, default is disabled(max retries is 0), it will auto retry for + +* network error +* server error with http status 429, 502, 503 and 504 + +```go +cfg.MaxRetries = 3 +``` + +#### Logging + +To set log level, you can see log with different level on **stdout**, you can also use it to enable or disable log. + +```go +// disable sdk log, default is log.InfoLevel +cfg.LogLevel = log.PanicLevel + +// enable sdk debug log level +// if debug log is enable, it will print all of request params and response body +cfg.LogLevel = log.DebugLevel +``` + +#### Timeout + +To set timeout for any network request, default is 30s. + +```go +cfg.Timeout = 30 * time.Second +``` + +#### Internal Usage + +the followed configuration should not be set in general usage. + +To set User-Agent, you can append custom UserAgent for any request, it also used for setting up special channel for customer. + +```go +cfg.UserAgent = "UCloud-CLI/0.1.0" +``` + +### Credential Config + +To set credential info for any request, credential is required for any client +```go +credential := auth.NewCredential() + +credential.PublicKey = os.Getenv("UCLOUD_PUBLIC_KEY") +credential.PrivateKey = os.Getenv("UCLOUD_PRIVATE_KEY") +``` diff --git a/docs/Usage.md b/docs/Usage.md new file mode 100644 index 00000000..8f2899f5 --- /dev/null +++ b/docs/Usage.md @@ -0,0 +1,106 @@ +## Usage + +### New Client + +sdk client for any ucloud product openapi service should constructed by client config and credential config, + +```go +import ( + "github.com/ucloud/ucloud-sdk-go/services/uhost" +) + +client := uhost.NewClient(&cfg, &credential) +``` + +### Build Request + +```go +req := client.NewCreateUHostInstanceRequest() + +req.Password = ucloud.String("xxx") +req.LoginMode = ucloud.String("Password") +req.Region = ucloud.String("cn-bj2") +req.Zone = ucloud.String("cn-bj2-04") +req.ImageId = ucloud.String("uimage-xxxx") +req.CPU = ucloud.Int(1) +req.Memory = ucloud.Int(1024) +``` + +#### Request Timeout + +To set request timeout for current request, it will overwrite the client Timeout at current request only. + +```go +req.WithTimeout(10 * time.Second) +``` + +#### Request Retring + +To set request max retries > 0 to enable auto retry, it will overwrite the client MaxRetries at current request only. + +```go +req.WithRetry(3) +``` + +### Send Request + +```go +resp, err := client.CreateUHostInstance(req) +log.Printf("%#v", resp.UHostIds) +``` + +### Error Handling + +#### General Usage + +In general usage, you can serialize error to string for free, use ``err.Error()`` or + +```go +fmt.Printf("got error: %s", err) +``` + +For bussiness error with RetCode > 0 at the body of server response, you can check it easily, such as + +```go +if uerr.IsCodeError(err) { + fmt.Printf("%v %s", e.Code(), e.Message()) +} else { + fmt.Printf("%s", e) +} +``` + +#### Advanced Usage + +In advanced usage, error could be infered ucloud sdk client error / server error, such as + +```go +import ( + uerr "github.com/ucloud/ucloud-sdk-go/ucloud/error" +) + +if err != nil { + switch err.(type) { + case uerr.(ClientError): + fmt.Printf("client error: %s", err) + case uerr.(ServerError): + fmt.Printf("server error: %s", err) + } +} +``` + +or enum by error name + +```go +import ( + uerr "github.com/ucloud/ucloud-sdk-go/ucloud/error" +) + +if e, ok := err.(uerr.Error); err != nil && ok { + switch e.Name() { + case uerr.ErrRetCode: + fmt.Printf("%v %s", e.Code(), e.Message()) + default: + fmt.Printf("%s", e) + } +} +``` diff --git a/example/uhost_example.go b/example/uhost_example.go deleted file mode 100644 index e12b8e93..00000000 --- a/example/uhost_example.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/ucloud/ucloud-sdk-go/service/uhost" - "github.com/ucloud/ucloud-sdk-go/ucloud" - "github.com/ucloud/ucloud-sdk-go/ucloud/auth" - "github.com/ucloud/ucloud-sdk-go/ucloud/utils" -) - -func main() { - - hostsvc := uhost.New(&ucloud.Config{ - Credentials: &auth.KeyPair{ - PublicKey: "ucloudsomeone@example.com1296235120854146120", - PrivateKey: "46f09bb9fab4f12dfc160dae12273d5332b5debe", - }, - Region: "cn-north-01", - ProjectID: "", - }) - - describeParams := uhost.DescribeUHostInstanceParams{ - Region: "cn-north-03", - Limit: 10, - Offset: 0, - } - - response, err := hostsvc.DescribeUHostInstance(&describeParams) - if err != nil { - fmt.Println(err) - } - utils.DumpVal(response) - - // createUhostParams := uhost.CreateUHostInstanceParams{ - // - // Region: "cn-north-03", - // ImageId: "uimage-j4fbrn", - // LoginMode: "Password", - // Password: "UGFzc3dvcmQx", - // CPU: 1, - // Memory:2048, - // Quantity:1, - // Quantity:1, - // Count: 1, - // } - // - // - // response, err := hostsvc.CreateUHostInstance(&createUhostParams) - // if err != nil { - // fmt.Println(err) - // } - // - // utils.DumpVal(response) - // - // - // // describeimage - // imageparams := uhost.DescribeImageParams{ - // Region: "cn-north-03", - // } - // - // - // imageresp, err := hostsvc.DescribeImage(&imageparams) - // if err != nil { - // fmt.Println(err) - // } - // - // utils.DumpVal(imageresp) -} diff --git a/examples/configure/README.md b/examples/configure/README.md new file mode 100644 index 00000000..8d59dbeb --- /dev/null +++ b/examples/configure/README.md @@ -0,0 +1,20 @@ +# UCloud SDK Configure Example + +## What is the goal + +Build an example configuration of sdk client. It will include all optional configuration item and it's usage. + +## Setup Environment + +```go +export UCLOUD_PUBLIC_KEY="your public key" +export UCLOUD_PRIVATE_KEY="your private key" +export UCLOUD_REGION="cn-bj2" +export UCLOUD_PROJECT_ID="your project id" +``` + +## How to run + +```sh +go run main.go +``` diff --git a/examples/configure/main.go b/examples/configure/main.go new file mode 100644 index 00000000..a3abf774 --- /dev/null +++ b/examples/configure/main.go @@ -0,0 +1,48 @@ +package main + +import ( + "os" + "time" + + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" + "github.com/ucloud/ucloud-sdk-go/ucloud/log" +) + +func main() { + cfg := ucloud.NewConfig() + + // set common region and project id for any request + // you can overwrite it by request + cfg.Region = "cn-bj2" + cfg.ProjectId = "xxx" + + // enable auto-retry for any request, default is disabled(max retries is 0) + // it will auto retry for + // * network error + // * server error with http status 429, 502, 503 and 504 + cfg.MaxRetries = 3 + + // disable sdk log, default is log.InfoLevel + cfg.LogLevel = log.PanicLevel + + // enable sdk debug log level + // if debug log is enable, it will print all of request params and response body + cfg.LogLevel = log.DebugLevel + + // set timeout for any request, default is 30s + cfg.Timeout = 30 * time.Second + + // the followed is used for private user and partner + // should not be set in general usage + + // custom User-Agent for any request + cfg.UserAgent = "UCloud-CLI/0.1.0" + + credential := auth.NewCredential() + + // set credential info for any request + // it is required + credential.PublicKey = os.Getenv("UCLOUD_PUBLIC_KEY") + credential.PrivateKey = os.Getenv("UCLOUD_PRIVATE_KEY") +} diff --git a/examples/retry/README.md b/examples/retry/README.md new file mode 100644 index 00000000..7e960ce9 --- /dev/null +++ b/examples/retry/README.md @@ -0,0 +1,20 @@ +# UCloud SDK Retry Example + +## What is the goal + +To enable retry for client or request. + +## Setup Environment + +```go +export UCLOUD_PUBLIC_KEY="your public key" +export UCLOUD_PRIVATE_KEY="your private key" +export UCLOUD_REGION="cn-bj2" +export UCLOUD_PROJECT_ID="your project id" +``` + +## How to run + +```sh +go run main.go +``` diff --git a/examples/retry/main.go b/examples/retry/main.go new file mode 100644 index 00000000..0a728864 --- /dev/null +++ b/examples/retry/main.go @@ -0,0 +1,32 @@ +package main + +import ( + "os" + + "github.com/ucloud/ucloud-sdk-go/services/ulb" + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" + "github.com/ucloud/ucloud-sdk-go/ucloud/log" +) + +func main() { + cfg := ucloud.NewConfig() + cfg.LogLevel = log.DebugLevel + cfg.Region = os.Getenv("UCLOUD_REGION") + cfg.ProjectId = os.Getenv("UCLOUD_PROJECT_ID") + + credential := auth.NewCredential() + credential.PrivateKey = os.Getenv("UCLOUD_PRIVATE_KEY") + credential.PublicKey = os.Getenv("UCLOUD_PUBLIC_KEY") + + client := ulb.NewClient(&cfg, &credential) + + req := client.NewDescribeULBRequest() + req.ULBId = ucloud.String("ulb-not-found-for-retry") + req.WithRetry(3) + + _, err := client.DescribeULB(req) + if err != nil { + log.Error(err) + } +} diff --git a/examples/two-tier/README.md b/examples/two-tier/README.md new file mode 100644 index 00000000..dab4437c --- /dev/null +++ b/examples/two-tier/README.md @@ -0,0 +1,20 @@ +# UCloud SDK Two-Tier Example + +## What is the goal + +Build a two-tier architecture with ulb and uhost, and remove all example data. + +## Setup Environment + +```go +export UCLOUD_PUBLIC_KEY="your public key" +export UCLOUD_PRIVATE_KEY="your private key" +export UCLOUD_REGION="cn-bj2" +export UCLOUD_PROJECT_ID="your project id" +``` + +## How to run + +```sh +go run main.go +``` diff --git a/examples/two-tier/main.go b/examples/two-tier/main.go new file mode 100644 index 00000000..cb43f1e6 --- /dev/null +++ b/examples/two-tier/main.go @@ -0,0 +1,290 @@ +package main + +import ( + "fmt" + "os" + "time" + + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" + "github.com/ucloud/ucloud-sdk-go/ucloud/log" + + "github.com/ucloud/ucloud-sdk-go/services/uhost" + "github.com/ucloud/ucloud-sdk-go/services/ulb" + "github.com/ucloud/ucloud-sdk-go/services/unet" +) + +const region = "cn-bj2" +const zone = "cn-bj2-05" +const imageID = "uimage-kg0w4u" + +var uhostClient *uhost.UHostClient +var unetClient *unet.UNetClient +var ulbClient *ulb.ULBClient + +func init() { + cfg := ucloud.NewConfig() + cfg.LogLevel = log.DebugLevel + cfg.Region = region + cfg.ProjectId = os.Getenv("UCLOUD_PROJECT_ID") + + credential := auth.NewCredential() + credential.PrivateKey = os.Getenv("UCLOUD_PRIVATE_KEY") + credential.PublicKey = os.Getenv("UCLOUD_PUBLIC_KEY") + + uhostClient = uhost.NewClient(&cfg, &credential) + unetClient = unet.NewClient(&cfg, &credential) + ulbClient = ulb.NewClient(&cfg, &credential) + + log.Info("setup clients ...") +} + +func main() { + uhostIDs, errs := createUHostBatch(2) + if len(errs) > 0 { + log.Error(errs) + return + } + + // teardown + defer deleteUHostBatch(uhostIDs) + + ulbID, err := createULB() + if err != nil { + log.Error(err) + return + } + + // teardown + defer deleteULB(ulbID) + + vserverID, err := createVServer(ulbID) + if err != nil { + log.Error(err) + return + } + + // teardown + defer deleteVServer(ulbID, vserverID) + + backendIDs, errs := allocateBackendBatch(ulbID, vserverID, uhostIDs) + if len(errs) > 0 { + log.Error(errs) + return + } + + // teardown + defer releaseBackendBatch(ulbID, vserverID, backendIDs) +} + +func createULB() (string, error) { + req := ulbClient.NewCreateULBRequest() + req.Tag = ucloud.String("sdk-example") + + resp, err := ulbClient.CreateULB(req) + if err != nil { + return "", err + } + + // wait for async action is completed + time.Sleep(5 * time.Second) + + return resp.ULBId, nil +} + +func deleteULB(ulbID string) error { + req := ulbClient.NewDeleteULBRequest() + req.ULBId = ucloud.String(ulbID) + + _, err := ulbClient.DeleteULB(req) + if err != nil { + return err + } + + return nil +} + +func createVServer(id string) (string, error) { + req := ulbClient.NewCreateVServerRequest() + req.ULBId = ucloud.String(id) + // req.Method = ucloud.String("ConsistentHash") + + resp, err := ulbClient.CreateVServer(req) + if err != nil { + return "", err + } + + // wait for async action is completed + time.Sleep(3 * time.Second) + + return resp.VServerId, nil +} + +func deleteVServer(ulbID, vserverID string) error { + req := ulbClient.NewDeleteVServerRequest() + req.ULBId = ucloud.String(ulbID) + req.VServerId = ucloud.String(vserverID) + + _, err := ulbClient.DeleteVServer(req) + if err != nil { + return err + } + + return nil +} + +func allocateBackendBatch(ulbID, vserverID string, uhostIDs []string) (ids []string, errors []error) { + for _, uhostID := range uhostIDs { + id, err := allocateBackend(ulbID, vserverID, uhostID) + if err != nil { + errors = append(errors, err) + } else { + ids = append(ids, id) + } + } + return +} + +func allocateBackend(ulbID, vserverID, uhostID string) (string, error) { + req := ulbClient.NewAllocateBackendRequest() + req.ULBId = ucloud.String(ulbID) + req.VServerId = ucloud.String(vserverID) + req.ResourceType = ucloud.String("UHost") + req.ResourceId = ucloud.String(uhostID) + req.Port = ucloud.Int(80) + + resp, err := ulbClient.AllocateBackend(req) + if err != nil { + return "", err + } + + return resp.BackendId, nil +} + +func releaseBackendBatch(ulbID, vserverID string, backendIDs []string) (errors []error) { + for _, backendID := range backendIDs { + err := releaseBackend(ulbID, backendID) + if err != nil { + errors = append(errors, err) + } + } + + return errors +} + +func releaseBackend(ulbID, backendID string) error { + req := ulbClient.NewReleaseBackendRequest() + req.ULBId = ucloud.String(ulbID) + req.BackendId = ucloud.String(backendID) + + _, err := ulbClient.ReleaseBackend(req) + if err != nil { + return err + } + + return nil +} + +func createUHostBatch(count int) (ids []string, errors []error) { + for i := 0; i < count; i++ { + id, err := createUHost(fmt.Sprintf("sdk-example-%d", i)) + if err != nil { + errors = append(errors, err) + } else { + ids = append(ids, id) + } + } + + // wait all uhost instance is running + if len(ids) > 0 { + if err := waitForState(ids, uhost.StateRunning); err != nil { + errors = append(errors, err) + } + } + + return +} + +func createUHost(name string) (string, error) { + req := uhostClient.NewCreateUHostInstanceRequest() + req.Name = ucloud.String(name) + req.Zone = ucloud.String(zone) // TODO: use random zone + req.ImageId = ucloud.String(imageID) // TODO: use random image + req.LoginMode = ucloud.String("Password") + req.Password = ucloud.String("somePassword_") + req.ChargeType = ucloud.String("Dynamic") + req.CPU = ucloud.Int(1) + req.Memory = ucloud.Int(1024) + req.Tag = ucloud.String("sdk-example") + + resp, err := uhostClient.CreateUHostInstance(req) + if err != nil { + return "", err + } + + return resp.UHostIds[0], nil +} + +func waitForState(ids []string, state uhost.State) error { + wait := uhostClient.NewWaitUntilUHostInstanceStateRequest() + wait.Interval = ucloud.TimeDuration(time.Second * 10) + wait.MaxAttempts = ucloud.Int(10) + wait.State = state + wait.IgnoreError = ucloud.Bool(true) + desc := uhostClient.NewDescribeUHostInstanceRequest() + desc.UHostIds = ids + wait.DescribeRequest = desc + + err := uhostClient.WaitUntilUHostInstanceState(wait) + if err != nil { + return err + } + return nil +} + +func deleteUHostBatch(ids []string) (errors []error) { + for _, id := range ids { + err := stopUHost(id) + if err != nil { + errors = append(errors, err) + } + } + + if err := waitForState(ids, uhost.StateStopped); err != nil { + errors = append(errors, err) + } + + for _, id := range ids { + err := deleteUHost(id) + if err != nil { + errors = append(errors, err) + } + } + + return +} + +func stopUHost(id string) error { + stop := uhostClient.NewStopUHostInstanceRequest() + stop.UHostId = ucloud.String(id) + stop.WithRetry(2) + + _, err := uhostClient.StopUHostInstance(stop) + if err != nil { + return err + } + + return nil +} + +func deleteUHost(id string) error { + req := uhostClient.NewTerminateUHostInstanceRequest() + req.UHostId = ucloud.String(id) + + _, err := uhostClient.TerminateUHostInstance(req) + if err != nil { + return err + } + + return nil +} diff --git a/examples/uhost/README.md b/examples/uhost/README.md new file mode 100644 index 00000000..b82d9317 --- /dev/null +++ b/examples/uhost/README.md @@ -0,0 +1,20 @@ +# UCloud SDK UHost Example + +## What is the goal + +Build a UHost instance. + +## Setup Environment + +```go +export UCLOUD_PUBLIC_KEY="your public key" +export UCLOUD_PRIVATE_KEY="your private key" +export UCLOUD_REGION="cn-bj2" +export UCLOUD_PROJECT_ID="your project id" +``` + +## How to run + +```sh +go run *.go +``` diff --git a/examples/uhost/config.go b/examples/uhost/config.go new file mode 100644 index 00000000..378df134 --- /dev/null +++ b/examples/uhost/config.go @@ -0,0 +1,28 @@ +package main + +import ( + "os" + + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" + "github.com/ucloud/ucloud-sdk-go/ucloud/log" +) + +const region = "cn-bj2" +const zone = "cn-bj2-05" +const imageID = "uimage-kg0w4u" + +func loadConfig() (*ucloud.Config, *auth.Credential) { + cfg := ucloud.NewConfig() + cfg.LogLevel = log.DebugLevel + cfg.Region = region + cfg.ProjectId = os.Getenv("UCLOUD_PROJECT_ID") + + credential := auth.NewCredential() + credential.PrivateKey = os.Getenv("UCLOUD_PRIVATE_KEY") + credential.PublicKey = os.Getenv("UCLOUD_PUBLIC_KEY") + + log.Info("setup clients ...") + + return &cfg, &credential +} diff --git a/examples/uhost/main.go b/examples/uhost/main.go new file mode 100644 index 00000000..9b567107 --- /dev/null +++ b/examples/uhost/main.go @@ -0,0 +1,78 @@ +package main + +import ( + "github.com/ucloud/ucloud-sdk-go/services/uhost" + "github.com/ucloud/ucloud-sdk-go/services/unet" + "github.com/ucloud/ucloud-sdk-go/ucloud" +) + +var uhostClient *uhost.UHostClient +var unetClient *unet.UNetClient + +func main() { + cfg, credential := loadConfig() + uhostClient = uhost.NewClient(cfg, credential) + unetClient = unet.NewClient(cfg, credential) + + eipID, err := createEIP("sdk-example-uhost") + if err != nil { + panic(err) + } + + uhostID, err := createUHost("sdk-example-uhost") + if err != nil { + panic(err) + } + + err = bindEIPToUHost(eipID, uhostID) + if err != nil { + panic(err) + } +} + +func bindEIPToUHost(eipID, uhostID string) error { + req := unetClient.NewBindEIPRequest() + req.EIPId = ucloud.String(eipID) + req.ResourceId = ucloud.String(uhostID) + req.ResourceType = ucloud.String("uhost") + + _, err := unetClient.BindEIP(req) + if err != nil { + return err + } + return nil +} + +func createEIP(name string) (string, error) { + req := unetClient.NewAllocateEIPRequest() + req.Name = ucloud.String(name) + req.Bandwidth = ucloud.Int(2) + req.OperatorName = ucloud.String("Bgp") + + resp, err := unetClient.AllocateEIP(req) + if err != nil { + return "", err + } + + return resp.EIPSet[0].EIPId, nil +} + +func createUHost(name string) (string, error) { + req := uhostClient.NewCreateUHostInstanceRequest() + req.Name = ucloud.String(name) + req.Zone = ucloud.String(zone) // TODO: use random zone + req.ImageId = ucloud.String(imageID) // TODO: use random image + req.LoginMode = ucloud.String("Password") + req.Password = ucloud.String("somePassword_") + req.ChargeType = ucloud.String("Dynamic") + req.CPU = ucloud.Int(1) + req.Memory = ucloud.Int(1024) + req.Tag = ucloud.String("sdk-example") + + resp, err := uhostClient.CreateUHostInstance(req) + if err != nil { + return "", err + } + + return resp.UHostIds[0], nil +} diff --git a/internal/services/README.md b/internal/services/README.md new file mode 100644 index 00000000..c5fed0c6 --- /dev/null +++ b/internal/services/README.md @@ -0,0 +1,10 @@ +# Internal Services + +Internal services used for daily testing with acceptance test cases. It should not used in any public usage. + +In general, it will include + +- describe action for statistics infomation of resource. +- validator action for monitoring program. +- action to backup some thing. +- action deprecated. diff --git a/internal/services/udataark/client.go b/internal/services/udataark/client.go new file mode 100644 index 00000000..39877799 --- /dev/null +++ b/internal/services/udataark/client.go @@ -0,0 +1,17 @@ +package udataark + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type UDataArkClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *UDataArkClient { + client := ucloud.NewClient(config, credential) + return &UDataArkClient{ + client: client, + } +} diff --git a/internal/services/udataark/describe_uhost_tm_meta.go b/internal/services/udataark/describe_uhost_tm_meta.go new file mode 100644 index 00000000..88535cbf --- /dev/null +++ b/internal/services/udataark/describe_uhost_tm_meta.go @@ -0,0 +1,57 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDataArk DescribeUhostTmMeta + +package udataark + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeUhostTmMetaRequest is request schema for DescribeUhostTmMeta action +type DescribeUhostTmMetaRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 本地盘主机填主机Id,网盘主机填系统盘id + UhostId *string `required:"true"` +} + +// DescribeUhostTmMetaResponse is response schema for DescribeUhostTmMeta action +type DescribeUhostTmMetaResponse struct { + response.CommonBase + + // JSON 格式的Snapshot列表, 详细参见DiskDataArkStatus + DataSet []DiskUDataArkStatus + + // 总备份的大小(byte) + UtmSize int + + // "normal" 正常状态 ,"in_init" 初始化中 + UtmStatus string + + // "enable" 可以Clone,"disable" 不能Clone + CloneAble string +} + +// NewDescribeUhostTmMetaRequest will create request of DescribeUhostTmMeta action. +func (c *UDataArkClient) NewDescribeUhostTmMetaRequest() *DescribeUhostTmMetaRequest { + req := &DescribeUhostTmMetaRequest{} + c.client.SetupRequest(req) + return req +} + +// DescribeUhostTmMeta - 获取主机方舟状态,判断方舟是否可用 +func (c *UDataArkClient) DescribeUhostTmMeta(req *DescribeUhostTmMetaRequest) (*DescribeUhostTmMetaResponse, error) { + var err error + var res DescribeUhostTmMetaResponse + + err = c.client.InvokeAction("DescribeUhostTmMeta", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/udataark/describe_vdisk_tm_list.go b/internal/services/udataark/describe_vdisk_tm_list.go new file mode 100644 index 00000000..d3e04069 --- /dev/null +++ b/internal/services/udataark/describe_vdisk_tm_list.go @@ -0,0 +1,57 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDataArk DescribeVDiskTmList + +package udataark + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeVDiskTmListRequest is request schema for DescribeVDiskTmList action +type DescribeVDiskTmListRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 磁盘ID + VDiskId *string `required:"true"` + + // 按备份类型过滤,"all"表示获取所有备份 ,目前仅支持“all” + SnapshotType *string `required:"true"` +} + +// DescribeVDiskTmListResponse is response schema for DescribeVDiskTmList action +type DescribeVDiskTmListResponse struct { + response.CommonBase + + // 返回数量 + TotalCount string + + // 备份链信息 + DataSet []DiskListDataSet + + // 备份链秒级信息 + FreshSet []DiskListFreshSet +} + +// NewDescribeVDiskTmListRequest will create request of DescribeVDiskTmList action. +func (c *UDataArkClient) NewDescribeVDiskTmListRequest() *DescribeVDiskTmListRequest { + req := &DescribeVDiskTmListRequest{} + c.client.SetupRequest(req) + return req +} + +// DescribeVDiskTmList - 查询磁盘备份链信息 +func (c *UDataArkClient) DescribeVDiskTmList(req *DescribeVDiskTmListRequest) (*DescribeVDiskTmListResponse, error) { + var err error + var res DescribeVDiskTmListResponse + + err = c.client.InvokeAction("DescribeVDiskTmList", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/udataark/types_disk_list_data_set.go b/internal/services/udataark/types_disk_list_data_set.go new file mode 100644 index 00000000..dc12edab --- /dev/null +++ b/internal/services/udataark/types_disk_list_data_set.go @@ -0,0 +1,40 @@ +package udataark + +/* + DiskListDataSet - 备份链记录 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type DiskListDataSet struct { + + // 快照ID + SnapshotId string + + // 快照名 + SnapshotName string + + // 快照类型,"minor" 小时级别增量备份 ,"major" 天级别增量备份 ,"base" base备份 ,"user" 用户手动备份 + SnapshotType string + + // 快照描述 + Comment string + + // 快照创建时间 + CreateTime int + + // 快照时间 + SnapshotTime int + + // 快照大小 + Size int + + // 是否用户手动快照,1 表示用户手动快照, 0表示非用户手动快照 + User int + + // 快照对应的方舟磁盘版本 + Version int + + // 快照状态,"ready" 表示等待merge ,"finish" 表示已经merge完成 + Status string +} diff --git a/internal/services/udataark/types_disk_list_fresh_set.go b/internal/services/udataark/types_disk_list_fresh_set.go new file mode 100644 index 00000000..6d75ee84 --- /dev/null +++ b/internal/services/udataark/types_disk_list_fresh_set.go @@ -0,0 +1,16 @@ +package udataark + +/* + DiskListFreshSet - 备份链秒级数据 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type DiskListFreshSet struct { + + // 秒级别快照数据开始时间 + StartTime int + + // 秒级别快照数据最新时间 + LatestTime int +} diff --git a/internal/services/udataark/types_disk_udata_ark_status.go b/internal/services/udataark/types_disk_udata_ark_status.go new file mode 100644 index 00000000..50299ffc --- /dev/null +++ b/internal/services/udataark/types_disk_udata_ark_status.go @@ -0,0 +1,37 @@ +package udataark + +/* + DiskUDataArkStatus - 磁盘方舟状态 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type DiskUDataArkStatus struct { + + // 磁盘Id + VdiskId string + + // 磁盘名 + VdiskName string + + // 磁盘描述 + VdiskDesc string + + // 是否系统盘 + SysVdisk int + + // 最近一次恢复时间 + RecoverTick int + + // 当前时间 + CurrentTick int + + // "normal" 正常状态"in_init" 初始化中 + UtmStatus string + + // "inprogress" 恢复进行中"succ" 恢复成功 "error" 恢复失败 "cancel" 恢复取消 + RecoverStatus string + + // 备份大小 + UtmSize int +} diff --git a/internal/services/udisk/check_udisk_allowance.go b/internal/services/udisk/check_udisk_allowance.go new file mode 100644 index 00000000..4c1537b5 --- /dev/null +++ b/internal/services/udisk/check_udisk_allowance.go @@ -0,0 +1,51 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk CheckUDiskAllowance + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CheckUDiskAllowanceRequest is request schema for CheckUDiskAllowance action +type CheckUDiskAllowanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 购买UDisk大小,单位:GB,范围[1~2000], 权限位控制可达8T,若需要请申请开通相关权限。 + Size *int `required:"true"` + + // 资源申请个数,默认为一个 + Count *int `required:"false"` +} + +// CheckUDiskAllowanceResponse is response schema for CheckUDiskAllowance action +type CheckUDiskAllowanceResponse struct { + response.CommonBase + + // 资源核查部分成功情况下,成功个数 + Count int +} + +// NewCheckUDiskAllowanceRequest will create request of CheckUDiskAllowance action. +func (c *UDiskClient) NewCheckUDiskAllowanceRequest() *CheckUDiskAllowanceRequest { + req := &CheckUDiskAllowanceRequest{} + c.client.SetupRequest(req) + return req +} + +// CheckUDiskAllowance - 检查UDisk资源余量 +func (c *UDiskClient) CheckUDiskAllowance(req *CheckUDiskAllowanceRequest) (*CheckUDiskAllowanceResponse, error) { + var err error + var res CheckUDiskAllowanceResponse + + err = c.client.InvokeAction("CheckUDiskAllowance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/udisk/client.go b/internal/services/udisk/client.go new file mode 100644 index 00000000..a58904bf --- /dev/null +++ b/internal/services/udisk/client.go @@ -0,0 +1,19 @@ +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +// UDiskClient is the client of ucloud disk +type UDiskClient struct { + client *ucloud.Client +} + +// NewClient will create an instance of UDiskClient +func NewClient(config *ucloud.Config, credential *auth.Credential) *UDiskClient { + client := ucloud.NewClient(config, credential) + return &UDiskClient{ + client: client, + } +} diff --git a/internal/services/udisk/clone_udisk_snapshot.go b/internal/services/udisk/clone_udisk_snapshot.go new file mode 100644 index 00000000..013df95b --- /dev/null +++ b/internal/services/udisk/clone_udisk_snapshot.go @@ -0,0 +1,69 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk CloneUDiskSnapshot + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CloneUDiskSnapshotRequest is request schema for CloneUDiskSnapshot action +type CloneUDiskSnapshotRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 实例名称 + Name *string `required:"true"` + + // 克隆父Snapshot的Id + SourceId *string `required:"true"` + + // 购买UDisk大小,单位:GB,范围[1~2000], 权限位控制可达8T,若需要请申请开通相关权限。 + Size *int `required:"true"` + + // Disk注释 + Comment *string `required:"false"` + + // Year , Month, Dynamic 默认: Dynamic + ChargeType *string `required:"false"` + + // 购买时长 默认: 1 + Quantity *int `required:"false"` + + // 是否开启数据方舟 默认:No + UDataArkMode *string `required:"false"` + + // 使用的代金券id + CouponId *string `required:"false"` +} + +// CloneUDiskSnapshotResponse is response schema for CloneUDiskSnapshot action +type CloneUDiskSnapshotResponse struct { + response.CommonBase + + // 创建UDisk Id + UDiskId []string +} + +// NewCloneUDiskSnapshotRequest will create request of CloneUDiskSnapshot action. +func (c *UDiskClient) NewCloneUDiskSnapshotRequest() *CloneUDiskSnapshotRequest { + req := &CloneUDiskSnapshotRequest{} + c.client.SetupRequest(req) + return req +} + +// CloneUDiskSnapshot - 从快照创建UDisk克隆 +func (c *UDiskClient) CloneUDiskSnapshot(req *CloneUDiskSnapshotRequest) (*CloneUDiskSnapshotResponse, error) { + var err error + var res CloneUDiskSnapshotResponse + + err = c.client.InvokeAction("CloneUDiskSnapshot", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/udisk/create_udisk_snapshot.go b/internal/services/udisk/create_udisk_snapshot.go new file mode 100644 index 00000000..d6326886 --- /dev/null +++ b/internal/services/udisk/create_udisk_snapshot.go @@ -0,0 +1,60 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk CreateUDiskSnapshot + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateUDiskSnapshotRequest is request schema for CreateUDiskSnapshot action +type CreateUDiskSnapshotRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 快照的UDisk的Id + UDiskId *string `required:"true"` + + // 快照名称 + Name *string `required:"true"` + + // Year , Month, Dynamic 默认: Dynamic + ChargeType *string `required:"false"` + + // 购买时长 默认: 1 + Quantity *int `required:"false"` + + // 快照描述 + Comment *string `required:"false"` +} + +// CreateUDiskSnapshotResponse is response schema for CreateUDiskSnapshot action +type CreateUDiskSnapshotResponse struct { + response.CommonBase + + // 快照Id + SnapshotId []string +} + +// NewCreateUDiskSnapshotRequest will create request of CreateUDiskSnapshot action. +func (c *UDiskClient) NewCreateUDiskSnapshotRequest() *CreateUDiskSnapshotRequest { + req := &CreateUDiskSnapshotRequest{} + c.client.SetupRequest(req) + return req +} + +// CreateUDiskSnapshot - 创建snapshot快照 +func (c *UDiskClient) CreateUDiskSnapshot(req *CreateUDiskSnapshotRequest) (*CreateUDiskSnapshotResponse, error) { + var err error + var res CreateUDiskSnapshotResponse + + err = c.client.InvokeAction("CreateUDiskSnapshot", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/uhost/client.go b/internal/services/uhost/client.go new file mode 100644 index 00000000..0943fb18 --- /dev/null +++ b/internal/services/uhost/client.go @@ -0,0 +1,17 @@ +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type UHostClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *UHostClient { + client := ucloud.NewClient(config, credential) + return &UHostClient{ + client: client, + } +} diff --git a/internal/services/uhost/delete_snapshot.go b/internal/services/uhost/delete_snapshot.go new file mode 100644 index 00000000..96b8fb8f --- /dev/null +++ b/internal/services/uhost/delete_snapshot.go @@ -0,0 +1,48 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost DeleteSnapshot + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeleteSnapshotRequest is request schema for DeleteSnapshot action +type DeleteSnapshotRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 快照Id + SnapshotId *string `required:"true"` +} + +// DeleteSnapshotResponse is response schema for DeleteSnapshot action +type DeleteSnapshotResponse struct { + response.CommonBase + + // 快照Id + SnapshotId string +} + +// NewDeleteSnapshotRequest will create request of DeleteSnapshot action. +func (c *UHostClient) NewDeleteSnapshotRequest() *DeleteSnapshotRequest { + req := &DeleteSnapshotRequest{} + c.client.SetupRequest(req) + return req +} + +// DeleteSnapshot - 删除快照 +func (c *UHostClient) DeleteSnapshot(req *DeleteSnapshotRequest) (*DeleteSnapshotResponse, error) { + var err error + var res DeleteSnapshotResponse + + err = c.client.InvokeAction("DeleteSnapshot", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/uhost/describe_snapshot.go b/internal/services/uhost/describe_snapshot.go new file mode 100644 index 00000000..89b25ee5 --- /dev/null +++ b/internal/services/uhost/describe_snapshot.go @@ -0,0 +1,75 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost DescribeSnapshot + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeSnapshotRequest is request schema for DescribeSnapshot action +type DescribeSnapshotRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 快照的资源ID,例如SnapshotIds.0代表希望获取信息的快照1,SnapshotIds.2代表快照2。 如果不传,则返回当前Region所有符合条件的快照。 + SnapshotIds []string `required:"false"` + + // 列表起始位置偏移量,默认为0 + Offset *int `required:"false"` + + // 返回数据长度,默认为20,最大10000000 + Limit *int `required:"false"` + + // 若传,则返回该主机下的所有快照 + UHostId *string `required:"false"` + + // 磁盘id,若磁盘传入,对应的UHostId必须一同传入 + DiskId *string `required:"false"` +} + +// DescribeSnapshotResponse is response schema for DescribeSnapshot action +type DescribeSnapshotResponse struct { + response.CommonBase + + // 满足条件的快照总数 + TotalCount int + + // 快照列表,每项参数可见下面SnapshotSet + UHostSnapshotSet []SnapshotSet + + // 总配额数 + TotalQuota int + + // 已使用的配额数 + TotalUsed int + + // 每块磁盘的快照配额 + PerDiskQuota int + + // 每块磁盘已经使用的配额数。如果不传DiskId,则返回0. + DiskUsed int +} + +// NewDescribeSnapshotRequest will create request of DescribeSnapshot action. +func (c *UHostClient) NewDescribeSnapshotRequest() *DescribeSnapshotRequest { + req := &DescribeSnapshotRequest{} + c.client.SetupRequest(req) + return req +} + +// DescribeSnapshot - 拉取快照列表 +func (c *UHostClient) DescribeSnapshot(req *DescribeSnapshotRequest) (*DescribeSnapshotResponse, error) { + var err error + var res DescribeSnapshotResponse + + err = c.client.InvokeAction("DescribeSnapshot", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/uhost/describe_uhost_lite.go b/internal/services/uhost/describe_uhost_lite.go new file mode 100644 index 00000000..0837caf9 --- /dev/null +++ b/internal/services/uhost/describe_uhost_lite.go @@ -0,0 +1,63 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost DescribeUHostLite + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeUHostLiteRequest is request schema for DescribeUHostLite action +type DescribeUHostLiteRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost主机的资源ID,例如UHostIds.0代表希望获取信息 的主机1,UHostIds.1代表主机2。 如果为空,则返回当前Region 所有符合条件的UHost实例。 + UHostIds []string `required:"false"` + + // 要查询的业务组名称 + Tag *string `required:"false"` + + // 列表起始位置偏移量,默认为0 + Offset *int `required:"false"` + + // 返回数据长度,默认为20,最大10000000 + Limit *int `required:"false"` + + // 云灾备,指明191 + ResourceType *int `required:"false"` +} + +// DescribeUHostLiteResponse is response schema for DescribeUHostLite action +type DescribeUHostLiteResponse struct { + response.CommonBase + + // 满足条件的UHostInstance总数 + TotalCount int + + // 云主机实例列表,每项参数可见下面 UHostInstanceSet + UHostSet []UHostInstanceSet +} + +// NewDescribeUHostLiteRequest will create request of DescribeUHostLite action. +func (c *UHostClient) NewDescribeUHostLiteRequest() *DescribeUHostLiteRequest { + req := &DescribeUHostLiteRequest{} + c.client.SetupRequest(req) + return req +} + +// DescribeUHostLite - 内部调用,列出UHost实例 +func (c *UHostClient) DescribeUHostLite(req *DescribeUHostLiteRequest) (*DescribeUHostLiteResponse, error) { + var err error + var res DescribeUHostLiteResponse + + err = c.client.InvokeAction("DescribeUHostLite", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/uhost/describe_uhost_recycle.go b/internal/services/uhost/describe_uhost_recycle.go new file mode 100644 index 00000000..905f0a3a --- /dev/null +++ b/internal/services/uhost/describe_uhost_recycle.go @@ -0,0 +1,57 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost DescribeUHostRecycle + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeUHostRecycleRequest is request schema for DescribeUHostRecycle action +type DescribeUHostRecycleRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost主机的资源ID,例如UHostIds.0代表希望获取信息 的主机1,UHostIds.1代表主机2。 如果为空,则返回当前Region 所有符合条件的UHost实例。 + UHostIds []string `required:"false"` + + // 列表起始位置偏移量,默认为0 + Offset *int `required:"false"` + + // 返回数据长度,默认为20,最大10000000 + Limit *int `required:"false"` +} + +// DescribeUHostRecycleResponse is response schema for DescribeUHostRecycle action +type DescribeUHostRecycleResponse struct { + response.CommonBase + + // 满足条件的UHostInstance总数 + TotalCount int + + // 云主机实例列表,每项参数可见下面 UHostInstanceSet + UHostSet []UHostInstanceSet +} + +// NewDescribeUHostRecycleRequest will create request of DescribeUHostRecycle action. +func (c *UHostClient) NewDescribeUHostRecycleRequest() *DescribeUHostRecycleRequest { + req := &DescribeUHostRecycleRequest{} + c.client.SetupRequest(req) + return req +} + +// DescribeUHostRecycle - 获取回收站中主机列表信息,并可根据数据中心,主机ID等参数进行过滤。 +func (c *UHostClient) DescribeUHostRecycle(req *DescribeUHostRecycleRequest) (*DescribeUHostRecycleResponse, error) { + var err error + var res DescribeUHostRecycleResponse + + err = c.client.InvokeAction("DescribeUHostRecycle", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/uhost/get_image_copy_progress.go b/internal/services/uhost/get_image_copy_progress.go new file mode 100644 index 00000000..2613b70e --- /dev/null +++ b/internal/services/uhost/get_image_copy_progress.go @@ -0,0 +1,48 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost GetImageCopyProgress + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetImageCopyProgressRequest is request schema for GetImageCopyProgress action +type GetImageCopyProgressRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // 镜像Id, 参见 [DescribeImage](describe_image.html) + ImageId *string `required:"true"` +} + +// GetImageCopyProgressResponse is response schema for GetImageCopyProgress action +type GetImageCopyProgressResponse struct { + response.CommonBase + + // 镜像复制进度百分比,精确到小数点后两位。100表示复制完成 + ProgressInfo string +} + +// NewGetImageCopyProgressRequest will create request of GetImageCopyProgress action. +func (c *UHostClient) NewGetImageCopyProgressRequest() *GetImageCopyProgressRequest { + req := &GetImageCopyProgressRequest{} + c.client.SetupRequest(req) + return req +} + +// GetImageCopyProgress - 获取镜像复制进度,通过镜像id,显示迁移进度百分比 +func (c *UHostClient) GetImageCopyProgress(req *GetImageCopyProgressRequest) (*GetImageCopyProgressResponse, error) { + var err error + var res GetImageCopyProgressResponse + + err = c.client.InvokeAction("GetImageCopyProgress", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/uhost/get_rest_resource.go b/internal/services/uhost/get_rest_resource.go new file mode 100644 index 00000000..5e463bb3 --- /dev/null +++ b/internal/services/uhost/get_rest_resource.go @@ -0,0 +1,66 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost GetRestResource + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetRestResourceRequest is request schema for GetRestResource action +type GetRestResourceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // Normal: 普通资源;SSD: ssd资源;BigData:大数据资源; GPU: gpu资源; 默认为GPU(目前只支持GPU) + ResourceType *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"false"` + + // 目标虚拟CPU核数,单位:个,范围:[2,32]。默认值为当前实例的CPU核数 + CPU *int `required:"false"` + + // 内存大小,单位:MB,范围[2048,65536],步长:2048,默认值为当前实例的内存大小 + Memory *int `required:"false"` + + // 数据盘大小,单位:GB,范围[10,1000]; SSD机型,单位:GB,范围[100,500];步长:10,默认值为当前实例的数据盘大小,数据盘不支持缩容,因此不允许输入比当前实例数据盘大小的值 + DiskSpace *int `required:"false"` + + // 系统盘大小,单位:GB,范围[20,100],步长:10,系统盘不支持缩容,因此不允许输入比当前实例系统盘小的值 + BootDiskSpace *int `required:"false"` +} + +// GetRestResourceResponse is response schema for GetRestResource action +type GetRestResourceResponse struct { + response.CommonBase + + // 返回资源数组 + ResourceInfos []ResourceInfoSet + + // 是否能成功升级 + UpgradeStatus bool +} + +// NewGetRestResourceRequest will create request of GetRestResource action. +func (c *UHostClient) NewGetRestResourceRequest() *GetRestResourceRequest { + req := &GetRestResourceRequest{} + c.client.SetupRequest(req) + return req +} + +// GetRestResource - 获取某种类型是否有剩余资源;主机升级配置前获取资源是否充足 +func (c *UHostClient) GetRestResource(req *GetRestResourceRequest) (*GetRestResourceResponse, error) { + var err error + var res GetRestResourceResponse + + err = c.client.InvokeAction("GetRestResource", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/uhost/get_uhost_renew_price.go b/internal/services/uhost/get_uhost_renew_price.go new file mode 100644 index 00000000..d7dd7821 --- /dev/null +++ b/internal/services/uhost/get_uhost_renew_price.go @@ -0,0 +1,48 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost GetUHostRenewPrice + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetUHostRenewPriceRequest is request schema for GetUHostRenewPrice action +type GetUHostRenewPriceRequest struct { + request.CommonBase + + // UHost实例ID + UHostId *string `required:"true"` + + // 计费类型。Year,Month,Dynamic,默认返回全部计费方式对应的价格 + ChargeType *string `required:"true"` +} + +// GetUHostRenewPriceResponse is response schema for GetUHostRenewPrice action +type GetUHostRenewPriceResponse struct { + response.CommonBase + + // 价格列表 UHostPriceSet + PriceSet []UHostPriceSet +} + +// NewGetUHostRenewPriceRequest will create request of GetUHostRenewPrice action. +func (c *UHostClient) NewGetUHostRenewPriceRequest() *GetUHostRenewPriceRequest { + req := &GetUHostRenewPriceRequest{} + c.client.SetupRequest(req) + return req +} + +// GetUHostRenewPrice - 获取主机续费价格 +func (c *UHostClient) GetUHostRenewPrice(req *GetUHostRenewPriceRequest) (*GetUHostRenewPriceResponse, error) { + var err error + var res GetUHostRenewPriceResponse + + err = c.client.InvokeAction("GetUHostRenewPrice", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/uhost/get_uimage_price.go b/internal/services/uhost/get_uimage_price.go new file mode 100644 index 00000000..8049652a --- /dev/null +++ b/internal/services/uhost/get_uimage_price.go @@ -0,0 +1,54 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost GetUImagePrice + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetUImagePriceRequest is request schema for GetUImagePrice action +type GetUImagePriceRequest struct { + request.CommonBase + + // 镜像Id + ImageId *string `required:"true"` + + // 购买个数,范围[1,5] + Count *int `required:"true"` + + // 计费类型。Year,Month,Dynamic,默认返回全部计费方式对应的价格 + ChargeType *string `required:"false"` + + // 购买时长, 默认为1 + Quantity *int `required:"false"` +} + +// GetUImagePriceResponse is response schema for GetUImagePrice action +type GetUImagePriceResponse struct { + response.CommonBase + + // 价格列表 UHostPriceSet + PriceSet []UHostPriceSet +} + +// NewGetUImagePriceRequest will create request of GetUImagePrice action. +func (c *UHostClient) NewGetUImagePriceRequest() *GetUImagePriceRequest { + req := &GetUImagePriceRequest{} + c.client.SetupRequest(req) + return req +} + +// GetUImagePrice - 获取镜像价格 +func (c *UHostClient) GetUImagePrice(req *GetUImagePriceRequest) (*GetUImagePriceResponse, error) { + var err error + var res GetUImagePriceResponse + + err = c.client.InvokeAction("GetUImagePrice", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/uhost/restore_uhost_disk.go b/internal/services/uhost/restore_uhost_disk.go new file mode 100644 index 00000000..524fbaa1 --- /dev/null +++ b/internal/services/uhost/restore_uhost_disk.go @@ -0,0 +1,54 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost RestoreUHostDisk + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// RestoreUHostDiskRequest is request schema for RestoreUHostDisk action +type RestoreUHostDiskRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 快照所属主机.仅当网盘数据盘未挂载时才可以不传。 + UHostId *string `required:"false"` + + // 主机上要恢复的磁盘Id. 对于本地盘主机,支持单独恢复系统盘或数据盘,也可以同时恢复系统盘和数据盘;对于网盘主机,只能恢复系统盘。从数据方舟恢复磁盘时必传。 + DiskIds []string `required:"false"` + + // 恢复的盘的时间戳,顺序与DiskIds.n保持对应。从数据方舟恢复磁盘时必传。 + RestoreTimestamps []string `required:"false"` + + // 快照Id. 对于本地盘主机,支持单独恢复系统盘或数据盘,也可以同时恢复系统盘和数据盘;对于网盘主机,只能恢复系统盘。从快照恢复磁盘时必传。 + SnapshotIds []string `required:"false"` +} + +// RestoreUHostDiskResponse is response schema for RestoreUHostDisk action +type RestoreUHostDiskResponse struct { + response.CommonBase +} + +// NewRestoreUHostDiskRequest will create request of RestoreUHostDisk action. +func (c *UHostClient) NewRestoreUHostDiskRequest() *RestoreUHostDiskRequest { + req := &RestoreUHostDiskRequest{} + c.client.SetupRequest(req) + return req +} + +// RestoreUHostDisk - 从数据方舟或者快照,恢复主机的磁盘。必须在关机状态下进行。 +func (c *UHostClient) RestoreUHostDisk(req *RestoreUHostDiskRequest) (*RestoreUHostDiskResponse, error) { + var err error + var res RestoreUHostDiskResponse + + err = c.client.InvokeAction("RestoreUHostDisk", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/uhost/types_resource_info_set.go b/internal/services/uhost/types_resource_info_set.go new file mode 100644 index 00000000..e6b4075b --- /dev/null +++ b/internal/services/uhost/types_resource_info_set.go @@ -0,0 +1,19 @@ +package uhost + +/* + ResourceInfoSet - 资源信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ResourceInfoSet struct { + + // 地域, 参见 [地域和可用区列表](../summary/regionlist.html) + Region string + + // 可用区,参见 [可用区列表](../summary/regionlist.html) + Zone string + + // Normal:标准机型, SATA_SSD: SATA SSD机型, BigData: 大数据机型,GPU: GPU型G1(原GPU型),GPU_G2:GPU型G2 + UHostType string +} diff --git a/internal/services/uhost/types_snapshot_set.go b/internal/services/uhost/types_snapshot_set.go new file mode 100644 index 00000000..9cf44fb6 --- /dev/null +++ b/internal/services/uhost/types_snapshot_set.go @@ -0,0 +1,46 @@ +package uhost + +/* + SnapshotSet - DescribeSnapshot + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type SnapshotSet struct { + + // 快照Id + SnapshotId string + + // 磁盘Id。仅当为网络盘时返回此id。 + DiskId string + + // 主机Id。若udisk没有挂载,则不返回。 + UHostId string + + // 磁盘类型,枚举值为:LocalBoot,本地系统盘;LocalData,本地数据盘;UDiskBoot,云系统盘;UDiskData,云数据盘 + DiskType string + + // 大小 + Size int + + // 快照状态,枚举值为:Normal,可用;Creating,制作中;Failed,制作失败 + State string + + // 快照名称 + SnapshotName string + + // 快照描述 + SnapshotDescription string + + // 创建成功时间,unix时间 + CreateTime int + + // 指定的制作快照时间,unix时间 + SnapshotTime int + + // 可用区id + ZoneId string + + // 资源名字。本地盘对应主机名字,网络盘对应udisk名字 + ResourceName string +} diff --git a/internal/services/uhost/types_uhost_disk_set.go b/internal/services/uhost/types_uhost_disk_set.go new file mode 100644 index 00000000..793d0237 --- /dev/null +++ b/internal/services/uhost/types_uhost_disk_set.go @@ -0,0 +1,25 @@ +package uhost + +/* + UHostDiskSet - DescribeUHostInstance + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostDiskSet struct { + + // 磁盘类型。系统盘: Boot,数据盘: Data,网络盘:Udisk + Type string + + // 磁盘ID + DiskId string + + // UDisk名字(仅当磁盘是UDisk时返回) + Name string + + // 磁盘盘符 + Drive string + + // 磁盘大小,单位: GB + Size int +} diff --git a/internal/services/uhost/types_uhost_instance_set.go b/internal/services/uhost/types_uhost_instance_set.go new file mode 100644 index 00000000..52aec6c1 --- /dev/null +++ b/internal/services/uhost/types_uhost_instance_set.go @@ -0,0 +1,106 @@ +package uhost + +/* + UHostInstanceSet - DescribeUHostInstance + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostInstanceSet struct { + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone string + + // UHost实例ID + UHostId string + + // UHost类型,枚举为:N1:标准型系列1;N2:标准型系列2 ;I1:高IO型系列1;I2:高IO型系列2;D1:大数据型系列1;G1:GPU型系列1;G2:GPU型系列2;G3:GPU型系列2 + UHostType string + + // 系统盘与数据盘的磁盘类型。 枚举值为:LocalDisk,本地磁盘; UDisk,云硬盘 + StorageType string + + // 镜像ID + ImageId string + + // 基础镜像ID(指当前自定义镜像的来源镜像) + BasicImageId string + + // 基础镜像名称(指当前自定义镜像的来源镜像) + BasicImageName string + + // 业务组名称 + Tag string + + // 备注 + Remark string + + // UHost实例名称 + Name string + + // 实例状态, 初始化: Initializing; 启动中: Starting; 运行中: Running; 关机中: Stopping; 关机: Stopped 安装失败: Install Fail; 重启中: Rebooting + State string + + // 创建时间,格式为Unix时间戳 + CreateTime int + + // 计费模式,枚举值为: Year,按年付费; Month,按月付费; Dynamic,按需付费(需开启权限); + ChargeType string + + // 到期时间,格式为Unix时间戳 + ExpireTime int + + // 虚拟CPU核数,单位: 个 + CPU int + + // 内存大小,单位: MB + Memory int + + // 是否自动续费,自动续费:“Yes”,不自动续费:“No” + AutoRenew string + + // 磁盘信息见 UHostDiskSet + DiskSet []UHostDiskSet + + // 详细信息见 UHostIPSet + IPSet []UHostIPSet + + // 网络增强。目前仅支持Normal和Super + NetCapability string + + // 网络状态 连接:Connected, 断开:NotConnected + NetworkState string + + // yes: 开启方舟; no,未开启方舟 + TimemachineFeature string + + // true: 开启热升级; false,未开启热升级 + HotplugFeature bool + + // 基础网络:Default;子网:Private + SubnetType string + + // 内网或者子网的IP地址 + IPs []string + + // Os名称 + OsName string + + // "Linux"或者"Windows" + OsType string + + // 删除时间,格式为Unix时间戳 + DeleteTime int + + // 主机系列:N2,表示系列2;N1,表示系列1 + HostType string + + // 主机的生命周期类型。目前仅支持Normal:普通; + LifeCycle string + + // 主机的 GPU 数量 + GPU int + + // 系统盘状态 Normal: 已初始化完成 + BootDiskState string +} diff --git a/internal/services/uhost/types_uhost_ipset.go b/internal/services/uhost/types_uhost_ipset.go new file mode 100644 index 00000000..d1b017a8 --- /dev/null +++ b/internal/services/uhost/types_uhost_ipset.go @@ -0,0 +1,22 @@ +package uhost + +/* + UHostIPSet - DescribeUHostInstance + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostIPSet struct { + + // 电信: China-telecom,联通: China-unicom, 国际: Internation,BGP: Bgp,内网: Private 双线: Duplet + Type string + + // IP资源ID (内网IP无对应的资源ID) + IPId string + + // IP地址 + IP string + + // IP对应的带宽, 单位: Mb (内网IP不显示带宽信息) + bandwidth int +} diff --git a/internal/services/uhost/types_uhost_price_set.go b/internal/services/uhost/types_uhost_price_set.go new file mode 100644 index 00000000..6891f303 --- /dev/null +++ b/internal/services/uhost/types_uhost_price_set.go @@ -0,0 +1,16 @@ +package uhost + +/* + UHostPriceSet - 主机价格 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostPriceSet struct { + + // 计费类型。Year,Month,Dynamic + ChargeType string + + // 价格,单位: 元,保留小数点后两位有效数字 + Price float32 +} diff --git a/internal/services/ulb/client.go b/internal/services/ulb/client.go new file mode 100644 index 00000000..648a2b1f --- /dev/null +++ b/internal/services/ulb/client.go @@ -0,0 +1,17 @@ +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type ULBClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *ULBClient { + client := ucloud.NewClient(config, credential) + return &ULBClient{ + client: client, + } +} diff --git a/internal/services/ulb/describe_ulbsimple.go b/internal/services/ulb/describe_ulbsimple.go new file mode 100644 index 00000000..685848c2 --- /dev/null +++ b/internal/services/ulb/describe_ulbsimple.go @@ -0,0 +1,63 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB DescribeULBSimple + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeULBSimpleRequest is request schema for DescribeULBSimple action +type DescribeULBSimpleRequest struct { + request.CommonBase + + // 数据偏移量,默认为0 + Offset *int `required:"false"` + + // 数据分页值,默认为10000 + Limit *string `required:"false"` + + // 负载均衡实例的Id。 若指定则返回指定的负载均衡实例的信息; 若不指定则返回当前数据中心中所有的负载均衡实例的信息 + ULBId *string `required:"false"` + + // ULB所属的VPC + VPCId *string `required:"false"` + + // ULB所属的子网ID + SubnetId *string `required:"false"` + + // ULB所属的业务组ID + BusinessId *string `required:"false"` +} + +// DescribeULBSimpleResponse is response schema for DescribeULBSimple action +type DescribeULBSimpleResponse struct { + response.CommonBase + + // 满足条件的ULB总数 + TotalCount int + + // ULB列表,每项参数详见 ULBSet + DataSet []ULBSet +} + +// NewDescribeULBSimpleRequest will create request of DescribeULBSimple action. +func (c *ULBClient) NewDescribeULBSimpleRequest() *DescribeULBSimpleRequest { + req := &DescribeULBSimpleRequest{} + c.client.SetupRequest(req) + return req +} + +// DescribeULBSimple - 获取ULB信息 +func (c *ULBClient) DescribeULBSimple(req *DescribeULBSimpleRequest) (*DescribeULBSimpleResponse, error) { + var err error + var res DescribeULBSimpleResponse + + err = c.client.InvokeAction("DescribeULBSimple", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/ulb/get_backend_metric_info.go b/internal/services/ulb/get_backend_metric_info.go new file mode 100644 index 00000000..b9bd0108 --- /dev/null +++ b/internal/services/ulb/get_backend_metric_info.go @@ -0,0 +1,54 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB GetBackendMetricInfo + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetBackendMetricInfoRequest is request schema for GetBackendMetricInfo action +type GetBackendMetricInfoRequest struct { + request.CommonBase + + // 后端rs的BackendId数组 + BackendIds []string `required:"true"` + + // 负载均衡实例的ID + ULBId *string `required:"false"` + + // VServer实例的ID + VServerId *string `required:"false"` +} + +// GetBackendMetricInfoResponse is response schema for GetBackendMetricInfo action +type GetBackendMetricInfoResponse struct { + response.CommonBase + + // 符合条件的总数 + TotalCount int + + // Backend列表,每项参数详见 DataSetBackend + DataSet []DataSetBackend +} + +// NewGetBackendMetricInfoRequest will create request of GetBackendMetricInfo action. +func (c *ULBClient) NewGetBackendMetricInfoRequest() *GetBackendMetricInfoRequest { + req := &GetBackendMetricInfoRequest{} + c.client.SetupRequest(req) + return req +} + +// GetBackendMetricInfo - 获取用于查询后端节点监控的元数据 +func (c *ULBClient) GetBackendMetricInfo(req *GetBackendMetricInfoRequest) (*GetBackendMetricInfoResponse, error) { + var err error + var res GetBackendMetricInfoResponse + + err = c.client.InvokeAction("GetBackendMetricInfo", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/ulb/get_vserver_metric_info.go b/internal/services/ulb/get_vserver_metric_info.go new file mode 100644 index 00000000..7c78970b --- /dev/null +++ b/internal/services/ulb/get_vserver_metric_info.go @@ -0,0 +1,57 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB GetVServerMetricInfo + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetVServerMetricInfoRequest is request schema for GetVServerMetricInfo action +type GetVServerMetricInfoRequest struct { + request.CommonBase + + // 项目ID + Project *string `required:"true"` + + // 负载均衡实例的ID + ULBId *string `required:"true"` + + // VServer实例的ID的数组 + VServerIds []string `required:"true"` + + // VServer 实例的 Id + VServerId *string `required:"false"` +} + +// GetVServerMetricInfoResponse is response schema for GetVServerMetricInfo action +type GetVServerMetricInfoResponse struct { + response.CommonBase + + // VServer列表 + DataSet []DataSetVServer + + // 符合条件的总数 + TotalCount int +} + +// NewGetVServerMetricInfoRequest will create request of GetVServerMetricInfo action. +func (c *ULBClient) NewGetVServerMetricInfoRequest() *GetVServerMetricInfoRequest { + req := &GetVServerMetricInfoRequest{} + c.client.SetupRequest(req) + return req +} + +// GetVServerMetricInfo - GetVServerMetricInfo +func (c *ULBClient) GetVServerMetricInfo(req *GetVServerMetricInfoRequest) (*GetVServerMetricInfoResponse, error) { + var err error + var res GetVServerMetricInfoResponse + + err = c.client.InvokeAction("GetVServerMetricInfo", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/ulb/types_data_set_backend.go b/internal/services/ulb/types_data_set_backend.go new file mode 100644 index 00000000..4f060c52 --- /dev/null +++ b/internal/services/ulb/types_data_set_backend.go @@ -0,0 +1,31 @@ +package ulb + +/* + DataSetBackend - GetBackendMetricInfo的DataSet + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type DataSetBackend struct { + + // 所添加的后端资源ID,(为ULB系统中使用,与资源自身ID无关) + BackendId string + + // 资源系统记录的后端节点id + MetricId string + + // 后端节点名称 + Name string + + // 后端节点业务组 + Tag string + + // 后端节点备注 + Remark string + + // 后端节点监听端口 + Port int + + // 后端节点内网ip + PrivateIP string +} diff --git a/internal/services/ulb/types_data_set_vserver.go b/internal/services/ulb/types_data_set_vserver.go new file mode 100644 index 00000000..654a7999 --- /dev/null +++ b/internal/services/ulb/types_data_set_vserver.go @@ -0,0 +1,31 @@ +package ulb + +/* + DataSetVServer - GetVServerMetricInfo的DataSet + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type DataSetVServer struct { + + // 所添加的后端资源ID,(为ULB系统中使用,与资源自身ID无关) + BackendId string + + // 监听器类型RequestProxy或者PacketsTransmit + ListenType string + + // 后端节点名称 + Name string + + // 后端节点业务组 + Tag string + + // 后端节点监听端口 + Port int + + // 资源系统记录的后端节点id + MetricId string + + // VServer 的 ID + VServerId string +} diff --git a/internal/services/ulb/types_policy_backend_set.go b/internal/services/ulb/types_policy_backend_set.go new file mode 100644 index 00000000..049eeb5f --- /dev/null +++ b/internal/services/ulb/types_policy_backend_set.go @@ -0,0 +1,25 @@ +package ulb + +/* + PolicyBackendSet - 内容转发下rs详细信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type PolicyBackendSet struct { + + // 所添加的后端资源在ULB中的对象ID,(为ULB系统中使用,与资源自身ID无关 + BackendId string + + // 后端资源的对象ID + ObjectId string + + // 所添加的后端资源服务端口 + Port int + + // 后端资源的内网IP + PrivateIP string + + // 后端资源的实例名称 + ResourceName string +} diff --git a/internal/services/ulb/types_ulbbackend_set.go b/internal/services/ulb/types_ulbbackend_set.go new file mode 100644 index 00000000..2e39b99c --- /dev/null +++ b/internal/services/ulb/types_ulbbackend_set.go @@ -0,0 +1,37 @@ +package ulb + +/* + ULBBackendSet - DescribeULB + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBBackendSet struct { + + // 后端资源实例的Id + BackendId string + + // 后端资源实例的类型 + ResourceType string + + // 后端资源实例的资源Id + ResourceId string + + // 后端资源实例的资源名字 + ResourceName string + + // 后端资源实例的内网IP + PrivateIP string + + // 后端资源实例服务的端口 + Port int + + // 后端资源实例的启用与否 + Enabled int + + // 后端资源实例的运行状态 + Status int + + // 后端资源实例的资源所在的子网的ID + SubnetId string +} diff --git a/internal/services/ulb/types_ulbipset.go b/internal/services/ulb/types_ulbipset.go new file mode 100644 index 00000000..521089ce --- /dev/null +++ b/internal/services/ulb/types_ulbipset.go @@ -0,0 +1,19 @@ +package ulb + +/* + ULBIPSet - DescribeULB + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBIPSet struct { + + // 弹性IP的运营商信息,枚举值为: Bgp:BGP IP International:国际IP + OperatorName string + + // 弹性IP地址 + EIP string + + // 弹性IP的ID + EIPId string +} diff --git a/internal/services/ulb/types_ulbpolicy_set.go b/internal/services/ulb/types_ulbpolicy_set.go new file mode 100644 index 00000000..b88e8efe --- /dev/null +++ b/internal/services/ulb/types_ulbpolicy_set.go @@ -0,0 +1,34 @@ +package ulb + +/* + ULBPolicySet - 内容转发详细列表 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBPolicySet struct { + + // 内容转发Id,默认内容转发类型下为空。 + PolicyId string + + // 内容类型,枚举值:Custom -> 客户自定义;Default -> 默认内容转发 + PolicyType string + + // 内容转发匹配字段的类型,枚举值:Domain -> 域名;Path -> 路径; 默认内容转发类型下为空 + Type string + + // 内容转发匹配字段;默认内容转发类型下为空。 + Match string + + // 内容转发优先级,范围[1,9999],数字越大优先级越高。默认内容转发规则下为0。 + PolicyPriority int + + // 所属VServerId + VServerId string + + // 默认内容转发类型下返回当前rs总数 + TotalCount int + + // 内容转发下rs的详细信息,参考PolicyBackendSet + BackendSet []PolicyBackendSet +} diff --git a/internal/services/ulb/types_ulbset.go b/internal/services/ulb/types_ulbset.go new file mode 100644 index 00000000..5f531049 --- /dev/null +++ b/internal/services/ulb/types_ulbset.go @@ -0,0 +1,61 @@ +package ulb + +/* + ULBSet - DescribeULB + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBSet struct { + + // 负载均衡的资源ID + ULBId string + + // 负载均衡的资源名称(内部记载,废弃) + ULBName string + + // 负载均衡的资源名称(资源系统中),缺省值“ULB” + Name string + + // 负载均衡的业务组名称,缺省值“Default” + Tag string + + // 负载均衡的备注,缺省值“” + Remark string + + // 带宽类型,枚举值为: 0,非共享带宽; 1,共享带宽 + BandwidthType int + + // 带宽 + Bandwidth int + + // ULB的创建时间,格式为Unix Timestamp + CreateTime int + + // ULB的到期时间,格式为Unix Timestamp + ExpireTime int + + // ULB的详细信息列表(废弃) + Resource []string + + // ULB的详细信息列表,具体结构见下方 ULBIPSet + IPSet []ULBIPSet + + // 负载均衡实例中存在的VServer实例列表,具体结构见下方 ULBVServerSet + VServerSet []ULBVServerSet + + // ULB 的类型 + ULBType string + + // ULB所在的VPC的ID + VPCId string + + // ULB 为 InnerMode 时,ULB 所属的子网ID,默认为空 + SubnetId string + + // ULB 所属的业务组ID + BusinessId string + + // ULB的内网IP,当ULBType为OuterMode时,该值为空 + PrivateIP string +} diff --git a/internal/services/ulb/types_ulbsslset.go b/internal/services/ulb/types_ulbsslset.go new file mode 100644 index 00000000..a5ec42a2 --- /dev/null +++ b/internal/services/ulb/types_ulbsslset.go @@ -0,0 +1,16 @@ +package ulb + +/* + ULBSSLSet - DescribeULB + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBSSLSet struct { + + // SSL证书的Id + SSLId string + + // SSL证书的名字 + SSLName string +} diff --git a/internal/services/ulb/types_ulbvserver_set.go b/internal/services/ulb/types_ulbvserver_set.go new file mode 100644 index 00000000..752dd83d --- /dev/null +++ b/internal/services/ulb/types_ulbvserver_set.go @@ -0,0 +1,58 @@ +package ulb + +/* + ULBVServerSet - DescribeULB + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBVServerSet struct { + + // VServer实例的Id + VServerId string + + // VServer实例的名字 + VServerName string + + // VServer实例的协议。 枚举值为:HTTP,TCP,UDP,HTTPS。 + Protocol string + + // VServer服务端口 + FrontendPort int + + // VServer负载均衡的模式,枚举值:Roundrobin -> 轮询;Source -> 源地址;ConsistentHash -> 一致性哈希;SourcePort -> 源地址(计算端口);ConsistentHashPort -> 一致性哈希(计算端口)。 + Method string + + // VServer会话保持方式。枚举值为: None -> 关闭会话保持; ServerInsert -> 自动生成; UserDefined -> 用户自定义。 + PersistenceType string + + // 根据PersistenceType确定: None或ServerInsert,此字段为空; UserDefined,此字段展示用户自定义会话string。 + PersistenceInfo string + + // 空闲连接的回收时间,单位:秒。 + ClientTimeout int + + // VServer的运行状态。枚举值: 0 -> rs全部运行正常;1 -> rs部分运行正常;2 -> rs全部运行异常。 + Status int + + // VServer绑定的SSL证书信息,具体结构见下方 ULBSSLSet + SSLSet []ULBSSLSet + + // 后端资源信息列表,具体结构见下方 ULBBackendSet + BackendSet []ULBBackendSet + + // 监听器类型,枚举值为: RequestProxy -> 请求代理;PacketsTransmit -> 报文转发 + ListenType string + + // 内容转发信息列表,具体结构见下方 ULBPolicySet + PolicySet []ULBPolicySet + + // 健康检查的类型,Port:端口,Path:路径 + MonitorType string + + // MonitorType 为 Path 时指定健康检查发送请求时HTTP HEADER 里的域名 + Domain string + + // MonitorType 为 Path 时指定健康检查发送请求时的路径,默认为 / + Path string +} diff --git a/internal/services/umon/client.go b/internal/services/umon/client.go new file mode 100644 index 00000000..42217c58 --- /dev/null +++ b/internal/services/umon/client.go @@ -0,0 +1,17 @@ +package umon + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type UMonClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *UMonClient { + client := ucloud.NewClient(config, credential) + return &UMonClient{ + client: client, + } +} diff --git a/internal/services/umon/describe_resource_metric.go b/internal/services/umon/describe_resource_metric.go new file mode 100644 index 00000000..b6c76714 --- /dev/null +++ b/internal/services/umon/describe_resource_metric.go @@ -0,0 +1,45 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UMon DescribeResourceMetric + +package umon + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeResourceMetricRequest is request schema for DescribeResourceMetric action +type DescribeResourceMetricRequest struct { + request.CommonBase + + // 资源类型 + ResourceType *string `required:"true"` +} + +// DescribeResourceMetricResponse is response schema for DescribeResourceMetric action +type DescribeResourceMetricResponse struct { + response.CommonBase + + // 指标信息集合 + DataSet []MetricInfo +} + +// NewDescribeResourceMetricRequest will create request of DescribeResourceMetric action. +func (c *UMonClient) NewDescribeResourceMetricRequest() *DescribeResourceMetricRequest { + req := &DescribeResourceMetricRequest{} + c.client.SetupRequest(req) + return req +} + +// DescribeResourceMetric - 获取资源支持监控指标信息 +func (c *UMonClient) DescribeResourceMetric(req *DescribeResourceMetricRequest) (*DescribeResourceMetricResponse, error) { + var err error + var res DescribeResourceMetricResponse + + err = c.client.InvokeAction("DescribeResourceMetric", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/umon/get_metric.go b/internal/services/umon/get_metric.go new file mode 100644 index 00000000..9ffa559b --- /dev/null +++ b/internal/services/umon/get_metric.go @@ -0,0 +1,60 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UMon GetMetric + +package umon + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetMetricRequest is request schema for GetMetric action +type GetMetricRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // 资源类型 + ResourceType *string `required:"true"` + + // 指标名称(不同ResourceType对应不同的MetricName) + MetricName []string `required:"true"` + + // 资源Id(目前除sharebandwidth可以不传入ResourceId外,其他资源必须传入,sharebandwidth不传入会默认使用获取到的第一个资源Id) + ResourceId *string `required:"false"` + + // 拉取最近多少秒的监控数据,默认1小时,即3600;最大1个月 + TimeRange *int `required:"false"` + + // 起始时间unixtimestamp,若传入TimeRange,此项忽略 + BeginTime *int `required:"false"` + + // 结束时间unixtimestamp,若传入TimeRange,此项忽略;若只传入BeginTime,此项默认为当前时间 + EndTime *int `required:"false"` +} + +// GetMetricResponse is response schema for GetMetric action +type GetMetricResponse struct { + response.CommonBase +} + +// NewGetMetricRequest will create request of GetMetric action. +func (c *UMonClient) NewGetMetricRequest() *GetMetricRequest { + req := &GetMetricRequest{} + c.client.SetupRequest(req) + return req +} + +// GetMetric - 获取监控数据 +func (c *UMonClient) GetMetric(req *GetMetricRequest) (*GetMetricResponse, error) { + var err error + var res GetMetricResponse + + err = c.client.InvokeAction("GetMetric", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/umon/types_metric_info.go b/internal/services/umon/types_metric_info.go new file mode 100644 index 00000000..28d8d717 --- /dev/null +++ b/internal/services/umon/types_metric_info.go @@ -0,0 +1,37 @@ +package umon + +/* + MetricInfo - GetMetricInfo-监控项信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type MetricInfo struct { + + // 指标名称 + MetricName string + + // 单位 + Unit string + + // 仅限内部使用 + ConversionFactor int + + // 数据类型 + Type string + + // 指标组名称,相同指标组前端可合并一张图显示 + MetricGroup string + + // 是否支持告警 + SupportAlarm string + + // 告警设置范围 + AlarmRange string + + // 数据上报频率 + Frequency string + + // 比较参数,可选GE,LE + CompareOption []string +} diff --git a/internal/services/unet/client.go b/internal/services/unet/client.go new file mode 100644 index 00000000..f0e18a78 --- /dev/null +++ b/internal/services/unet/client.go @@ -0,0 +1,17 @@ +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type UNetClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *UNetClient { + client := ucloud.NewClient(config, credential) + return &UNetClient{ + client: client, + } +} diff --git a/internal/services/unet/describe_security_group.go b/internal/services/unet/describe_security_group.go new file mode 100644 index 00000000..14e87672 --- /dev/null +++ b/internal/services/unet/describe_security_group.go @@ -0,0 +1,51 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DescribeSecurityGroup + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeSecurityGroupRequest is request schema for DescribeSecurityGroup action +type DescribeSecurityGroupRequest struct { + request.CommonBase + + // 绑定防火墙组的资源类型,如uhost + ResourceType *string `required:"false"` + + // 绑定防火墙组的资源ID + ResourceId *string `required:"false"` + + // 防火墙ID + GroupId *string `required:"false"` +} + +// DescribeSecurityGroupResponse is response schema for DescribeSecurityGroup action +type DescribeSecurityGroupResponse struct { + response.CommonBase + + // 获取的防火墙组详细信息 参见 UnetSecurityGroupSet + DataSet []UnetSecurityGroupSet +} + +// NewDescribeSecurityGroupRequest will create request of DescribeSecurityGroup action. +func (c *UNetClient) NewDescribeSecurityGroupRequest() *DescribeSecurityGroupRequest { + req := &DescribeSecurityGroupRequest{} + c.client.SetupRequest(req) + return req +} + +// DescribeSecurityGroup - 获取防火墙组信息 +func (c *UNetClient) DescribeSecurityGroup(req *DescribeSecurityGroupRequest) (*DescribeSecurityGroupResponse, error) { + var err error + var res DescribeSecurityGroupResponse + + err = c.client.InvokeAction("DescribeSecurityGroup", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/unet/describe_share_bandwidth_price.go b/internal/services/unet/describe_share_bandwidth_price.go new file mode 100644 index 00000000..bdbd194d --- /dev/null +++ b/internal/services/unet/describe_share_bandwidth_price.go @@ -0,0 +1,54 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DescribeShareBandwidthPrice + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeShareBandwidthPriceRequest is request schema for DescribeShareBandwidthPrice action +type DescribeShareBandwidthPriceRequest struct { + request.CommonBase + + // 付费方式, 预付费:Year 按年,Month 按月,Dynamic 按需;后付费:Postpay(按月) + ChargeType *string `required:"true"` + + // 共享带宽值(预付费)/共享带宽峰值(后付费) + ShareBandwidth *int `required:"true"` + + // 购买时长(预付费) + Quantity *int `required:"false"` + + // 共享带宽保底值(后付费) + ShareBandwidthGuarantee *int `required:"false"` +} + +// DescribeShareBandwidthPriceResponse is response schema for DescribeShareBandwidthPrice action +type DescribeShareBandwidthPriceResponse struct { + response.CommonBase + + // 共享带宽总价 + TotalPrice int +} + +// NewDescribeShareBandwidthPriceRequest will create request of DescribeShareBandwidthPrice action. +func (c *UNetClient) NewDescribeShareBandwidthPriceRequest() *DescribeShareBandwidthPriceRequest { + req := &DescribeShareBandwidthPriceRequest{} + c.client.SetupRequest(req) + return req +} + +// DescribeShareBandwidthPrice - 获取共享带宽价格 +func (c *UNetClient) DescribeShareBandwidthPrice(req *DescribeShareBandwidthPriceRequest) (*DescribeShareBandwidthPriceResponse, error) { + var err error + var res DescribeShareBandwidthPriceResponse + + err = c.client.InvokeAction("DescribeShareBandwidthPrice", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/internal/services/unet/types_security_group_rule_set.go b/internal/services/unet/types_security_group_rule_set.go new file mode 100644 index 00000000..4bb9ad90 --- /dev/null +++ b/internal/services/unet/types_security_group_rule_set.go @@ -0,0 +1,25 @@ +package unet + +/* + SecurityGroupRuleSet - DescribeSecurityGroup + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type SecurityGroupRuleSet struct { + + // 源地址 + SrcIP string + + // 优先级 + Priority int + + // 协议类型 + ProtocolType string + + // 目标端口 + DstPort string + + // 防火墙动作 + RuleAction string +} diff --git a/internal/services/unet/types_unet_security_group_set.go b/internal/services/unet/types_unet_security_group_set.go new file mode 100644 index 00000000..77787bd4 --- /dev/null +++ b/internal/services/unet/types_unet_security_group_set.go @@ -0,0 +1,25 @@ +package unet + +/* + UnetSecurityGroupSet - DescribeSecurityGroup + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UnetSecurityGroupSet struct { + + // 防火墙ID,可选,为空时不显示Rule + GroupId string + + // 防火墙组的名称 + GroupName string + + // 防火墙组创建时间,格式为Unix Timestamp + CreateTime string + + // 防火墙组类型,枚举值为: 0:用户自定义防火墙; 1:默认Web防火墙; 2:默认非Web防火墙 + Type string + + // 防火墙组中的规则表,参见 SecurityGroupRuleSet + Rule []SecurityGroupRuleSet +} diff --git a/internal/utest/case.go b/internal/utest/case.go new file mode 100644 index 00000000..9e7695c3 --- /dev/null +++ b/internal/utest/case.go @@ -0,0 +1,54 @@ +package utest + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + + uerr "github.com/ucloud/ucloud-sdk-go/ucloud/error" +) + +// TestValidator is the validator function +type TestValidator func(interface{}, error) error + +// TestCase is the case definition of test case +type TestCase struct { + Invoker func() (interface{}, error) + Validators []TestValidator + MaxRetries int + RetryInterval time.Duration + T *testing.T +} + +// Run will run the test case with retry +func (t *TestCase) Run() (interface{}, error) { + for i := 0; i < t.MaxRetries+1; i++ { + resp, err := t.Invoker() + + isFailed := false + for _, validator := range t.Validators { + if err := validator(resp, err); err != nil { + isFailed = true + if i != t.MaxRetries { + t.T.Logf("skip validate error for retry, %s", err) + continue + } + assert.NoError(t.T, err) + } + } + + if i == t.MaxRetries || !isFailed { + if err != nil && !uerr.IsCodeError(err) { + assert.NoError(t.T, err) + return resp, err + } + return resp, nil + } + + <-time.After(t.RetryInterval) + } + + // never reached here + return nil, nil +} diff --git a/internal/utest/comparator_utils.go b/internal/utest/comparator_utils.go new file mode 100644 index 00000000..ffa94096 --- /dev/null +++ b/internal/utest/comparator_utils.go @@ -0,0 +1,134 @@ +package utest + +import ( + "encoding/json" + "fmt" + "reflect" + "strconv" + + "github.com/pkg/errors" +) + +func checkFloats(a, b interface{}, checkFunc func(float64, float64) (bool, error)) (bool, error) { + aVal, bVal, err := toFloats(a, b) + if err != nil { + return false, err + } + return checkFunc(aVal, bVal) +} + +func checkStrings(a, b interface{}, checkFunc func(string, string) (bool, error)) (bool, error) { + aVal, bVal, err := toStrings(a, b) + if err != nil { + return false, err + } + return checkFunc(aVal, bVal) +} + +func checkLens(a, b interface{}, checkFunc func(int, int) (bool, error)) (bool, error) { + aVal, err := toLen(a) + if err != nil { + return false, err + } + + bVal, err := toInt(b) + if err != nil { + return false, err + } + + return checkFunc(aVal, bVal) +} + +func toFloats(a, b interface{}) (float64, float64, error) { + aVal, err := toFloat(a) + if err != nil { + return 0.0, 0.0, err + } + + bVal, err := toFloat(b) + if err != nil { + return 0.0, 0.0, err + } + + return roundTo(aVal, 2), roundTo(bVal, 2), nil +} + +func roundTo(num float64, perc uint) float64 { + val, _ := strconv.ParseFloat(fmt.Sprintf("%."+strconv.Itoa(int(perc))+"f", num), 64) + return val +} + +func toStrings(a, b interface{}) (string, string, error) { + aVal, err := toString(a) + if err != nil { + return "", "", err + } + + bVal, err := toString(b) + if err != nil { + return "", "", err + } + + return aVal, bVal, nil +} + +func toFloat(v interface{}) (float64, error) { + rv := reflect.ValueOf(v) + + switch rv.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(rv.Int()), nil + case reflect.Float32, reflect.Float64: + return rv.Float(), nil + case reflect.String: + val, err := strconv.ParseFloat(rv.String(), 64) + if err != nil { + return 0.0, errors.Errorf("value %s cannot convert to float", err) + } + return val, nil + default: + return 0.0, errors.Errorf("value %s cannot convert to float", v) + } +} + +func toInt(v interface{}) (int, error) { + rv := reflect.ValueOf(v) + + switch rv.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return int(rv.Int()), nil + case reflect.Float32, reflect.Float64: + return int(rv.Float()), nil + case reflect.String: + val, err := strconv.Atoi(rv.String()) + if err != nil { + return 0.0, errors.Errorf("value %s cannot convert to int", err) + } + return val, nil + default: + return 0, errors.Errorf("value %s cannot convert to int", v) + } +} + +func toString(v interface{}) (string, error) { + rv := reflect.ValueOf(v) + switch rv.Kind() { + case reflect.Struct: + b, err := json.Marshal(v) + return string(b), err + default: + return fmt.Sprintf("%+v", v), nil + } +} + +var canGetLengthTypes = []reflect.Kind{reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String} + +func toLen(v interface{}) (int, error) { + rv := reflect.ValueOf(v) + for _, t := range canGetLengthTypes { + if rv.Kind() == t { + return rv.Len(), nil + } + } + return 0, errors.Errorf("value %+v cannot get length", v) +} diff --git a/internal/utest/comparator_utils_test.go b/internal/utest/comparator_utils_test.go new file mode 100644 index 00000000..2701689c --- /dev/null +++ b/internal/utest/comparator_utils_test.go @@ -0,0 +1,223 @@ +package utest + +import ( + "testing" +) + +func Test_checkFloats(t *testing.T) { + type args struct { + a interface{} + b interface{} + checkFunc func(float64, float64) (bool, error) + } + tests := []struct { + name string + args args + want bool + wantErr bool + }{ + {"ok", args{"0.1", "0.1", func(a, b float64) (bool, error) { return a == b, nil }}, true, false}, + {"check_false", args{"0.1", "0.2", func(a, b float64) (bool, error) { return a == b, nil }}, false, false}, + {"check_round", args{"0.675", "0.676", func(a, b float64) (bool, error) { return a == b, nil }}, true, false}, + + {"not_float", args{"0.1", "x", func(a, b float64) (bool, error) { return a == b, nil }}, false, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := checkFloats(tt.args.a, tt.args.b, tt.args.checkFunc) + if (err != nil) != tt.wantErr { + t.Errorf("checkFloats() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("checkFloats() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_toString(t *testing.T) { + type args struct { + v interface{} + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + {"ok", args{"1"}, "1", false}, + {"ok_int", args{1}, "1", false}, + {"ok_float", args{1.0}, "1", false}, + {"ok_struct", args{struct{ Name string }{Name: "1"}}, "{Name:1}", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := toString(tt.args.v) + if (err != nil) != tt.wantErr { + t.Errorf("toString() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("toString() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_checkStrings(t *testing.T) { + type Test struct { + Name string + } + + type args struct { + a interface{} + b interface{} + checkFunc func(string, string) (bool, error) + } + tests := []struct { + name string + args args + want bool + wantErr bool + }{ + {"ok", args{"a", "a", func(a, b string) (bool, error) { return a == b, nil }}, true, false}, + {"ok_int", args{1, 1, func(a, b string) (bool, error) { return a == b, nil }}, true, false}, + {"ok_float", args{1.0, 1.0, func(a, b string) (bool, error) { return a == b, nil }}, true, false}, + {"check_false", args{"a", "b", func(a, b string) (bool, error) { return a == b, nil }}, false, false}, + {"check_struct", args{Test{"a"}, Test{"b"}, func(a, b string) (bool, error) { return a == b, nil }}, false, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := checkStrings(tt.args.a, tt.args.b, tt.args.checkFunc) + if (err != nil) != tt.wantErr { + t.Errorf("checkStrings() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("checkStrings() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_checkLens(t *testing.T) { + type args struct { + a interface{} + b interface{} + checkFunc func(int, int) (bool, error) + } + tests := []struct { + name string + args args + want bool + wantErr bool + }{ + {"ok", args{[]string{"1"}, []string{"1"}, func(a, b int) (bool, error) { return a == b, nil }}, true, false}, + {"ok_str", args{"1", "1", func(a, b int) (bool, error) { return a == b, nil }}, true, false}, + {"check_false", args{[]string{"1"}, []string{}, func(a, b int) (bool, error) { return a == b, nil }}, false, false}, + + {"cannot_get_length", args{"0.1", 1, func(a, b int) (bool, error) { return a == b, nil }}, false, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := checkLens(tt.args.a, tt.args.b, tt.args.checkFunc) + if (err != nil) != tt.wantErr { + t.Errorf("checkLens() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("checkLens() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_toFloat(t *testing.T) { + type args struct { + v interface{} + } + tests := []struct { + name string + args args + want float64 + wantErr bool + }{ + {"ok_int", args{1}, 1.0, false}, + {"ok_float", args{1.0}, 1.0, false}, + {"ok_str", args{"0.1"}, 0.1, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := toFloat(tt.args.v) + if (err != nil) != tt.wantErr { + t.Errorf("toFloat() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("toFloat() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_roundTo(t *testing.T) { + type args struct { + num float64 + perc uint + } + tests := []struct { + name string + args args + want float64 + }{ + {"ok", args{1.123, 2}, 1.12}, + {"ok_int", args{1, 2}, 1.00}, + + {"ok_to_even", args{0.675, 2}, 0.68}, + {"ok_to_odd", args{0.685, 2}, 0.69}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := roundTo(tt.args.num, tt.args.perc); got != tt.want { + t.Errorf("roundTo() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_toLen(t *testing.T) { + type test struct { + Name string + } + type args struct { + v interface{} + } + tests := []struct { + name string + args args + want int + wantErr bool + }{ + {"str", args{"abc"}, 3, false}, + {"slice", args{[]string{"abc"}}, 1, false}, + {"map", args{map[string]string{"Name": "abc"}}, 1, false}, + + {"int", args{123}, 0, true}, + {"float", args{0.675}, 0, true}, + {"nil", args{nil}, 0, true}, + {"struct", args{test{Name: "abc"}}, 0, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := toLen(tt.args.v) + if (err != nil) != tt.wantErr { + t.Errorf("toLen() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("toLen() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/internal/utest/comparators.go b/internal/utest/comparators.go new file mode 100644 index 00000000..9d0c5832 --- /dev/null +++ b/internal/utest/comparators.go @@ -0,0 +1,194 @@ +package utest + +import ( + "reflect" + "regexp" + "strings" + + "github.com/pkg/errors" +) + +type CompareFunc func(interface{}, interface{}) (bool, error) +type Comparators struct { + comparators map[string]CompareFunc +} + +// NewComparators will return Comparators +func NewComparators() Comparators { + comparators := map[string]CompareFunc{ + "eq": eq, + "equals": eq, + "==": eq, + + "abs_eq": absEq, + "abs_equals": absEq, + + "lt": lt, + "less_than": lt, + + "le": le, + "less_than_or_equals": le, + + "gt": gt, + "greater_than": gt, + + "ge": ge, + "greater_than_or_equals": ge, + + "ne": ne, + "not_equals": ne, + + "str_eq": strEq, + "string_equals": strEq, + + "float_eq": floatEq, + "float_equals": floatEq, + + "len_eq": lenEq, + "length_equals": lenEq, + "count_eq": lenEq, + + "len_gt": lenGt, + "count_gt": lenGt, + "length_greater_than": lenGt, + "count_greater_than": lenGt, + + "len_ge": lenGe, + "count_ge": lenGe, + "length_greater_than_or_equals": lenGe, + "count_greater_than_or_equals": lenGe, + + "len_lt": lenLt, + "count_lt": lenLt, + "length_less_than": lenLt, + "count_less_than": lenLt, + + "len_le": lenLe, + "count_le": lenLe, + "length_less_than_or_equals": lenLe, + "count_less_than_or_equals": lenLe, + + "contains": contains, + "contained_by": containedBy, + "type": typeEq, + "regex": regexMatch, + "startswith": startsWith, + "endswith": endsWith, + "object_contains": objectContains, + "object_not_contains": objectNotContains, + } + return Comparators{comparators} +} + +// Get will return a comparator function by name +func (c *Comparators) Get(name string) CompareFunc { + if fn, ok := c.comparators[name]; ok { + return fn + } + return nil +} + +func eq(a, b interface{}) (bool, error) { + return reflect.DeepEqual(a, b), nil +} + +func absEq(a, b interface{}) (bool, error) { + return checkFloats(a, b, func(aVal, bVal float64) (bool, error) { return aVal == bVal, nil }) +} + +func lt(a, b interface{}) (bool, error) { + return checkFloats(a, b, func(aVal, bVal float64) (bool, error) { return aVal < bVal, nil }) +} + +func le(a, b interface{}) (bool, error) { + return checkFloats(a, b, func(aVal, bVal float64) (bool, error) { return aVal <= bVal, nil }) +} + +func gt(a, b interface{}) (bool, error) { + return checkFloats(a, b, func(aVal, bVal float64) (bool, error) { return aVal > bVal, nil }) +} + +func ge(a, b interface{}) (bool, error) { + return checkFloats(a, b, func(aVal, bVal float64) (bool, error) { return aVal >= bVal, nil }) +} + +func ne(a, b interface{}) (bool, error) { + return checkFloats(a, b, func(aVal, bVal float64) (bool, error) { return aVal != bVal, nil }) +} + +func floatEq(a, b interface{}) (bool, error) { + return checkFloats(a, b, func(aVal, bVal float64) (bool, error) { return aVal == bVal, nil }) +} + +func strEq(a, b interface{}) (bool, error) { + return checkStrings(a, b, func(aVal, bVal string) (bool, error) { return aVal == bVal, nil }) +} + +func lenEq(a, b interface{}) (bool, error) { + return checkLens(a, b, func(aVal, bVal int) (bool, error) { return aVal == bVal, nil }) +} + +func lenGt(a, b interface{}) (bool, error) { + return checkLens(a, b, func(aVal, bVal int) (bool, error) { return aVal > bVal, nil }) +} + +func lenGe(a, b interface{}) (bool, error) { + return checkLens(a, b, func(aVal, bVal int) (bool, error) { return aVal >= bVal, nil }) +} + +func lenLt(a, b interface{}) (bool, error) { + return checkLens(a, b, func(aVal, bVal int) (bool, error) { return aVal < bVal, nil }) +} + +func lenLe(a, b interface{}) (bool, error) { + return checkLens(a, b, func(aVal, bVal int) (bool, error) { return aVal <= bVal, nil }) +} + +func contains(a, b interface{}) (bool, error) { + rv := reflect.ValueOf(a) + if rv.Kind() != reflect.Slice && rv.Kind() != reflect.Array { + return false, errors.Errorf("val must be contained by an iterable type, got %s", rv.String()) + } + + for i := 0; i < rv.Len(); i++ { + isEq, err := strEq(rv.Index(i), b) + if isEq { + return true, nil + } + + if err != nil { + return false, err + } + } + + return false, nil +} + +func containedBy(a, b interface{}) (bool, error) { + return contains(b, a) +} + +func typeEq(a, b interface{}) (bool, error) { + typeVal, _ := toString(b) + return reflect.ValueOf(a).Type().String() == typeVal, nil +} + +func regexMatch(a, b interface{}) (bool, error) { + return checkStrings(a, b, func(aVal, bVal string) (bool, error) { return regexp.MatchString(bVal, aVal) }) +} + +func startsWith(a, b interface{}) (bool, error) { + return checkStrings(a, b, func(aVal, bVal string) (bool, error) { return strings.HasPrefix(aVal, bVal), nil }) +} + +func endsWith(a, b interface{}) (bool, error) { + return checkStrings(a, b, func(aVal, bVal string) (bool, error) { return strings.HasSuffix(aVal, bVal), nil }) +} + +func objectContains(a, b interface{}) (bool, error) { + return checkStrings(a, b, func(aVal, bVal string) (bool, error) { return strings.Contains(aVal, bVal), nil }) +} + +func objectNotContains(a, b interface{}) (bool, error) { + return checkStrings(a, b, func(aVal, bVal string) (bool, error) { return !strings.Contains(aVal, bVal), nil }) +} diff --git a/internal/utest/comparators_test.go b/internal/utest/comparators_test.go new file mode 100644 index 00000000..8c9a2018 --- /dev/null +++ b/internal/utest/comparators_test.go @@ -0,0 +1,32 @@ +package utest + +import "testing" + +func Test_lenEq(t *testing.T) { + type args struct { + a interface{} + b interface{} + } + tests := []struct { + name string + args args + want bool + wantErr bool + }{ + {"equal", args{[]map[string]string{{"foo": "bar"}}, 1}, true, false}, + {"not_equal", args{[]map[string]string{{"foo": "bar"}}, 2}, false, false}, + {"error", args{[]map[string]string{{"foo": "bar"}}, "x"}, false, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := lenEq(tt.args.a, tt.args.b) + if (err != nil) != tt.wantErr { + t.Errorf("lenEq() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("lenEq() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/internal/utest/ctx.go b/internal/utest/ctx.go new file mode 100644 index 00000000..0205176a --- /dev/null +++ b/internal/utest/ctx.go @@ -0,0 +1,77 @@ +package utest + +import ( + "testing" + + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" +) + +type TestContext struct { + T *testing.T + + Vars map[string]interface{} + Comparators *Comparators +} + +// NewTestContext will return a new TestContext +func NewTestContext() TestContext { + comparators := NewComparators() + + return TestContext{ + Vars: make(map[string]interface{}), + Comparators: &comparators, + } +} + +// SetVar will set the variable of test context +func (ctx *TestContext) SetVar(name string, value interface{}) { + ctx.Vars[name] = value +} + +// GetVar will return the variable of test context +func (ctx *TestContext) GetVar(name string) interface{} { + if v, ok := ctx.Vars[name]; ok { + return v + } + return "" +} + +// NewValidator will return new validator to validate value is expected +func (ctx *TestContext) NewValidator(valuePath string, expected interface{}, comparator string) TestValidator { + compratorFunc := ctx.Comparators.Get(comparator) + return func(resp interface{}, respErr error) error { + v, err := GetValue(resp, valuePath) + if err != nil { + return errors.Errorf("cannot get value from %s, %s", valuePath, err) + } + + ok, err := compratorFunc(v, expected) + if err != nil { + return errors.Errorf("want %#v %s %#v, %s", v, comparator, expected, err) + } + + if !ok { + return errors.Errorf("want %#v %s %#v, but false", v, comparator, expected) + } + + return nil + } +} + +// MustString will check error is nil and return the string value +func (ctx *TestContext) MustString(v string, err error) string { + assert.NoError(ctx.T, err) + return v +} + +// Must will check error is nil and return the value +func (ctx *TestContext) Must(v interface{}, err error) interface{} { + assert.NoError(ctx.T, err) + return v +} + +// NoError will check error is nil +func (ctx *TestContext) NoError(err error) { + assert.NoError(ctx.T, err) +} diff --git a/internal/utest/functions.go b/internal/utest/functions.go new file mode 100644 index 00000000..a61faf37 --- /dev/null +++ b/internal/utest/functions.go @@ -0,0 +1,198 @@ +package utest + +import ( + "crypto/rand" + "encoding/json" + "fmt" + "strconv" + "strings" + "time" + + "github.com/pkg/errors" +) + +var zoneImages = map[string]string{ + "cn-bj1-01": "uimage-zf2xoa", + "cn-bj2-02": "uimage-ixczxu", // origin is uimage-u0k3m3 + "cn-bj2-03": "b2689fc412ee5fa108fa5b23ed2e00e6", + "cn-bj2-04": "uimage-rq2kat", + "cn-bj2-05": "uimage-kg0w4u", + "cn-sh-01": "uimage-65fa28", + "cn-sh2-01": "uimage-p0c51y", + "cn-sh2-02": "uimage-of3pac", + "cn-gd-02": "uimage-b54e21", + "hk-01": "uimage-g3hvlg", + "hk-02": "uimage-gcs1cr", + "us-ca-01": "uimage-0duw4w", + "us-ws-01": "uimage-ggiase", + "ge-fra-01": "uimage-unynvz", + "th-bkk-01": "uimage-2bsbiy", + "kr-seoul-01": "uimage-kxrlft", + "sg-01": "uimage-oqpggx", + "tw-kh-01": "uimage-hwgsqi", + "rus-mosc-01": "uimage-cgfvqy", + "jpn-tky-01": "uimage-jshpqn", + "tw-tp-01": "uimage-toxa1t", + "cn-zj-01": "uimage-vv0zdq", +} + +// GetZoneImage will return the image id for zone +func GetZoneImage(input interface{}) (string, error) { + zone, err := toString(input) + if err != nil { + return "", err + } + if img, ok := zoneImages[zone]; ok { + return img, nil + } + return "", errors.Errorf("cannot get zone image, invalid zone %s", zone) +} + +// GetImageResource will return the image id for region and zone +func GetImageResource(inputRegion, inputZone interface{}) (string, error) { + return GetZoneImage(inputZone) +} + +var regionImages = map[string]string{ + "cn-bj1": "uimage-zf2xoa", + "cn-bj2": "uimage-rq2kat", + "cn-sh": "uimage-65fa28", + "cn-sh2": "uimage-p0c51y", + "cn-gd": "uimage-b54e21", + "hk": "uimage-gcs1cr", + "us-ca": "uimage-0duw4w", + "us-ws": "uimage-ggiase", + "ge-fra": "uimage-unynvz", + "th-bkk": "uimage-2bsbiy", + "kr-seoul": "uimage-kxrlft", + "sg": "uimage-oqpggx", + "tw-kh": "uimage-hwgsqi", + "rus-mosc": "uimage-cgfvqy", + "jpn-tky": "uimage-jshpqn", + "tw-tp": "uimage-toxa1t", + "cn-zj": "uimage-vv0zdq", +} + +// GetRegionImage will return the image id for region +func GetRegionImage(input interface{}) (string, error) { + region, err := toString(input) + if err != nil { + return "", err + } + if img, ok := regionImages[region]; ok { + return img, nil + } + return "", errors.Errorf("cannot get region image, invalid region %s", region) +} + +func GetTimestamp(input interface{}) (string, error) { + strLen, err := toInt(input) + if err != nil { + return getTimestamp(13) + } + + return getTimestamp(strLen) +} + +func getTimestamp(strLen int) (string, error) { + if strLen < 0 || 19 < strLen { + return "", errors.Errorf("timestamp length can only between 0 and 16") + } + return strconv.FormatInt(time.Now().UnixNano(), 10)[:strLen], nil +} + +func Concat(input ...interface{}) (string, error) { + return joinAsString("", input...) +} + +func ConcatWithVertical(input ...interface{}) (string, error) { + return joinAsString("|", input...) +} + +func joinAsString(sep string, input ...interface{}) (string, error) { + items := []string{} + for _, item := range input { + s, err := toString(item) + if err != nil { + return "", err + } + items = append(items, s) + } + return strings.Join(items, sep), nil +} + +// Calculate will to calculate two number by operator +func Calculate(op string, a, b interface{}) (int, error) { + aVal, err := toInt(a) + if err != nil { + return 0, err + } + + bVal, err := toInt(b) + if err != nil { + return 0, err + } + + switch op { + case "+": + return aVal + bVal, nil + case "-": + return aVal - bVal, nil + case "*": + return aVal * bVal, nil + default: + return 0, errors.Errorf("function Calculate has not support %s", op) + } +} + +// SearchValue will search key/value in an collection and return the value of destination key +func SearchValue(arr interface{}, originKey string, originValue interface{}, destKey string) (interface{}, error) { + jsonPayload, err := json.Marshal(arr) + if err != nil { + return "", nil + } + + mArr := []map[string]interface{}{} + err = json.Unmarshal(jsonPayload, &mArr) + if err != nil { + return "", err + } + + for _, m := range mArr { + if val, ok := m[originKey]; !ok { + continue + } else { + a, _ := toString(originValue) + b, _ := toString(val) + if a != b { + continue + } + } + + if val, ok := m[destKey]; ok { + return val, nil + } + } + + return "", errors.Errorf("value of key: %s is not found", destKey) +} + +func GetUUID() (string, error) { + items := []string{} + for _, strLen := range []int{8, 4, 4, 16} { + s, err := getRandomString(strLen) + if err != nil { + return "", err + } + items = append(items, s) + } + return strings.Join(items, "-"), nil +} + +func getRandomString(strLen int) (string, error) { + b := make([]byte, strLen) + if _, err := rand.Read(b); err != nil { + return "", errors.Errorf("cannot generate random string") + } + return fmt.Sprintf("%X", b), nil +} diff --git a/internal/utest/functions_test.go b/internal/utest/functions_test.go new file mode 100644 index 00000000..83c9c50c --- /dev/null +++ b/internal/utest/functions_test.go @@ -0,0 +1,256 @@ +package utest + +import ( + "strings" + "testing" +) + +func TestGetZoneImage(t *testing.T) { + type args struct { + zone interface{} + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + {"ok", args{"cn-bj2-02"}, "uimage-ixczxu", false}, + {"invalid_zone", args{"cn-bj100"}, "", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := GetZoneImage(tt.args.zone) + if (err != nil) != tt.wantErr { + t.Errorf("GetZoneImage() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("GetZoneImage() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestGetImageResource(t *testing.T) { + type args struct { + region interface{} + zone interface{} + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + {"ok", args{"", "cn-bj2-02"}, "uimage-ixczxu", false}, + {"invalid_zone", args{"", "cn-bj100"}, "", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := GetImageResource(tt.args.region, tt.args.zone) + if (err != nil) != tt.wantErr { + t.Errorf("GetImageResource() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("GetImageResource() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestGetRegionImage(t *testing.T) { + type args struct { + input interface{} + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + {"ok", args{"cn-bj2"}, "uimage-rq2kat", false}, + {"invalid_region", args{"cn-bj100"}, "", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := GetRegionImage(tt.args.input) + if (err != nil) != tt.wantErr { + t.Errorf("GetRegionImage() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("GetRegionImage() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestGetTimestamp(t *testing.T) { + type args struct { + input interface{} + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + // {"ok", args{"13"}, "", false}, // TODO: how to mock? + {"invalid_length", args{"20"}, "", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := GetTimestamp(tt.args.input) + if (err != nil) != tt.wantErr { + t.Errorf("GetTimestamp() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("GetTimestamp() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestConcatWithVertical(t *testing.T) { + type args struct { + input []interface{} + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + {"ok", args{[]interface{}{"foo", 42}}, "foo|42", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := ConcatWithVertical(tt.args.input...) + if (err != nil) != tt.wantErr { + t.Errorf("ConcatWithVertical() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("ConcatWithVertical() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestConcat(t *testing.T) { + type args struct { + input []interface{} + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + {"ok", args{[]interface{}{"foo", 42}}, "foo42", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := Concat(tt.args.input...) + if (err != nil) != tt.wantErr { + t.Errorf("Concat() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("Concat() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestCalculate(t *testing.T) { + type args struct { + a interface{} + b interface{} + op string + } + tests := []struct { + name string + args args + want int + wantErr bool + }{ + {"sum", args{"1", "1", "+"}, 2, false}, + {"sub", args{"2", "1", "-"}, 1, false}, + {"multi", args{"1", "1", "*"}, 1, false}, + + {"number", args{"1", 1, "+"}, 2, false}, + {"not number", args{"1", "x", "+"}, 0, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := Calculate(tt.args.op, tt.args.a, tt.args.b) + if (err != nil) != tt.wantErr { + t.Errorf("Calculate() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("Calculate() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestSearchValue(t *testing.T) { + type testStruct struct { + Name string + Data int + } + type args struct { + arr interface{} + originKey string + originValue string + destKey string + } + tests := []struct { + name string + args args + want interface{} + wantErr bool + }{ + { + "ok", + args{ + []testStruct{ + testStruct{Name: "foo", Data: 42}, + testStruct{Name: "bar", Data: 142}, + }, + "Name", + "foo", + "Data", + }, + 42, + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := SearchValue(tt.args.arr, tt.args.originKey, tt.args.originValue, tt.args.destKey) + if (err != nil) != tt.wantErr { + t.Errorf("SearchValue() error = %v, wantErr %v", err, tt.wantErr) + return + } + gotS, _ := toString(got) + wantS, _ := toString(tt.want) + if gotS != wantS { + t.Errorf("SearchValue() = %#v, want %#v", got, tt.want) + } + }) + } +} + +func TestGetUUID(t *testing.T) { + uuidS, _ := GetUUID() + length := len(strings.Split(uuidS, "-")) + if length != 4 { + t.Errorf("GetUUID() length is %v, want %v", length, 4) + } +} diff --git a/internal/utest/utils.go b/internal/utest/utils.go new file mode 100644 index 00000000..24e6dd99 --- /dev/null +++ b/internal/utest/utils.go @@ -0,0 +1,99 @@ +package utest + +import ( + "reflect" + "strconv" + + "github.com/pkg/errors" + "github.com/ucloud/ucloud-sdk-go/private/utils" + "github.com/ucloud/ucloud-sdk-go/ucloud" +) + +// GetValue will return the value of an object by path +func GetValue(obj interface{}, path string) (interface{}, error) { + if obj == nil { + return "", nil + } + + v, err := utils.ValueAtPath(obj, path) + if err != nil { + return "", err + } + + return v, nil +} + +// SetReqValue will set value into pointer referenced or slice +func SetReqValue(addr interface{}, field string, value interface{}) error { + rv := reflect.ValueOf(addr) + if rv.IsValid() == false { + return errors.Errorf("struct is invalid") + } + + for rv.Kind() == reflect.Ptr { + if rv.IsNil() { + return errors.Errorf("struct is nil") + } + rv = rv.Elem() + } + + if rv.Kind() != reflect.Struct { + return errors.Errorf("got type %s, expected struct", rv.Kind().String()) + } + + rv = rv.FieldByName(field) + if !rv.IsValid() { + return errors.Errorf("struct field %s is invalid", field) + } + + if rv.Kind() != reflect.Ptr && rv.Kind() != reflect.Slice { + return errors.Errorf("only support pointer and slice type value") + } + + if !rv.CanSet() { + return errors.Errorf("cannot set %s, field cannot be set", field) + } + + s, _ := toString(value) + v, err := convertValueWithType(rv.Type().Elem(), s) + if err != nil { + return err + } + + if rv.Kind() == reflect.Ptr { + rv.Set(v) + } else if rv.Kind() == reflect.Slice { + rv.Set(reflect.Append(rv, v.Elem())) + } + + return nil +} + +func convertValueWithType(typ reflect.Type, value string) (reflect.Value, error) { + v := reflect.Zero(typ) + + switch typ.Kind() { + case reflect.String: + v = reflect.ValueOf(&value) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + intValue, err := strconv.ParseInt(value, 10, 64) + if err != nil { + return v, err + } + v = reflect.ValueOf(ucloud.Int(int(intValue))) + case reflect.Float32, reflect.Float64: + floatValue, err := strconv.ParseFloat(value, 64) + if err != nil { + return v, err + } + v = reflect.ValueOf(ucloud.Float64(floatValue)) + case reflect.Bool: + boolValue, err := strconv.ParseBool(value) + if err != nil { + return v, err + } + v = reflect.ValueOf(ucloud.Bool(boolValue)) + } + + return v, nil +} diff --git a/internal/utest/utils_test.go b/internal/utest/utils_test.go new file mode 100644 index 00000000..66c02556 --- /dev/null +++ b/internal/utest/utils_test.go @@ -0,0 +1,90 @@ +package utest + +import ( + "testing" + + "github.com/ucloud/ucloud-sdk-go/ucloud" +) + +func TestGetValue(t *testing.T) { + type testSet struct { + Name string + } + + type test struct { + RetCode int + Message string + DataSet []testSet + } + + type args struct { + obj interface{} + path string + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + { + "ok", + args{ + test{1, "some error", []testSet{testSet{"1"}}}, + "DataSet.0.Name", + }, + "1", + false, + }, + { + "ok", + args{ + test{1, "some error", []testSet{testSet{"1"}}}, + "RetCode", + }, + "1", + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := GetValue(tt.args.obj, tt.args.path) + if (err != nil) != tt.wantErr { + t.Errorf("GetValue() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("GetValue() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestSetReqValue(t *testing.T) { + type Test struct { + Name *string + CPU *int + IPs []string + } + testObj := Test{} + + SetReqValue(&testObj, "Name", "name") + if *testObj.Name != "name" { + t.Errorf("SetReqValue() = %#v, want %v", ucloud.StringValue(testObj.Name), "name") + } + + SetReqValue(&testObj, "CPU", "1") + if *testObj.CPU != 1 { + t.Errorf("SetReqValue() = %#v, want %v", ucloud.IntValue(testObj.CPU), 1) + } + + SetReqValue(&testObj, "IPs", "192.168.0.1") + if testObj.IPs[0] != "192.168.0.1" { + t.Errorf("SetReqValue() = %#v, want %v", testObj.IPs[0], "192.168.0.1") + } + + SetReqValue(&testObj, "IPs", "192.168.0.1") + if testObj.IPs[0] != "192.168.0.1" { + t.Errorf("SetReqValue() = %#v, want %v", testObj.IPs[0], "192.168.0.1") + } +} diff --git a/private/protocol/http/client.go b/private/protocol/http/client.go new file mode 100644 index 00000000..3f1c0188 --- /dev/null +++ b/private/protocol/http/client.go @@ -0,0 +1,79 @@ +package http + +import ( + "io/ioutil" + "net/http" + "time" + + "github.com/pkg/errors" +) + +// HttpClient used to send a real request via http to server +type HttpClient struct { +} + +// NewHttpClient will create a new HttpClient instance +func NewHttpClient() HttpClient { + return HttpClient{} +} + +// Send will send a real http request to remote server +func (c *HttpClient) Send(req *HttpRequest) (*HttpResponse, error) { + // build http.Client with timeout settings + httpClient, err := c.buildHTTPClient(req.GetTimeout()) + if err != nil { + return nil, err + } + + // convert sdk http request to origin http.Request + httpReq, err := req.buildHTTPRequest() + if err != nil { + return nil, err + } + + // TODO: enable tracer via `httptrace` package + resp, err := c.doHTTPRequest(httpClient, httpReq) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *HttpClient) buildHTTPClient(timeout time.Duration) (*http.Client, error) { + httpClient := http.Client{} + if timeout != 0 { + httpClient = http.Client{Timeout: timeout} + } + return &httpClient, nil +} + +func (c *HttpClient) doHTTPRequest(client *http.Client, req *http.Request) (*HttpResponse, error) { + // send request + httpResp, err := client.Do(req) + if err != nil { + return nil, errors.Errorf("cannot send request, %s", err) + } + defer httpResp.Body.Close() + + // raise status error + if httpResp.StatusCode >= 400 { + return nil, NewStatusError(httpResp.StatusCode, httpResp.Status) + } + + // read content + body, err := ioutil.ReadAll(httpResp.Body) + if err != nil { + return nil, errors.Errorf("cannot read response, %s", err) + } + + // build response wrapper + resp := NewHttpResponse() + resp.setHttpReponse(httpResp) + resp.setBody(body) + return resp, nil +} + +func (c *HttpClient) buildHTTPRequestWithTracer(req *http.Request) (*http.Request, error) { + // TODO: implement trace via httptrace + return req, nil +} diff --git a/private/protocol/http/defaults.go b/private/protocol/http/defaults.go new file mode 100644 index 00000000..899602ad --- /dev/null +++ b/private/protocol/http/defaults.go @@ -0,0 +1,13 @@ +package http + +import ( + "time" +) + +// DefaultHeaders defined default http headers +var DefaultHeaders = map[string]string{ + "Content-Type": "application/x-www-form-urlencoded", + // "X-SDK-VERSION": VERSION, +} + +var DefaultTimeout = 30 * time.Second diff --git a/private/protocol/http/error.go b/private/protocol/http/error.go new file mode 100644 index 00000000..6e10b957 --- /dev/null +++ b/private/protocol/http/error.go @@ -0,0 +1,23 @@ +package http + +import ( + "fmt" +) + +// StatusError is the error for http status code >= 400 +type StatusError struct { + StatusCode int + Message string +} + +func (e StatusError) Error() string { + return fmt.Sprintf("http status %v error", e.StatusCode) +} + +// NewStatusError will create a new status error +func NewStatusError(code int, message string) StatusError { + return StatusError{ + StatusCode: code, + Message: message, + } +} diff --git a/private/protocol/http/http_test.go b/private/protocol/http/http_test.go new file mode 100644 index 00000000..2164464e --- /dev/null +++ b/private/protocol/http/http_test.go @@ -0,0 +1,77 @@ +package http + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestHTTPRequest(t *testing.T) { + req := NewHttpRequest() + + k, v := "Content-Type", "application/json" + req.SetHeader(k, v) + assert.Equal(t, req.GetHeaderMap()[k], v) + + method := "GET" + req.SetMethod(method) + assert.Equal(t, req.GetMethod(), method) + + k, v = "foo", "bar" + req.SetQuery(k, v) + assert.Equal(t, req.GetQueryMap()[k], v) + + req.SetQueryString("foo1=bar") + assert.Equal(t, req.GetQueryMap()["foo1"], "bar") + + req.SetQueryString("foo1=bar1") + assert.Equal(t, req.GetQueryMap()["foo1"], "bar1") + + timeout := 1 * time.Second + req.SetTimeout(timeout) + assert.Equal(t, req.GetTimeout(), timeout) + + req.SetURL("http://api.ucloud.cn?foo2=bar") + assert.Equal(t, req.GetQueryMap()["foo2"], "bar") + + body := []byte("data") + req.SetRequestBody(body) + assert.Equal(t, req.GetRequestBody(), body) +} + +func TestClientSend(t *testing.T) { + req := NewHttpRequest() + req.SetMethod("GET") + req.SetURL("https://httpbin.org/get") + + client := NewHttpClient() + resp, err := client.Send(&req) + assert.Nil(t, err) + assert.Equal(t, 200, resp.GetStatusCode()) + assert.NotEmpty(t, resp.GetBody()) +} + +func TestHTTPStatusError(t *testing.T) { + req := NewHttpRequest() + req.SetMethod("GET") + req.SetURL("https://httpbin.org/status/503") + + client := NewHttpClient() + resp, err := client.Send(&req) + assert.Nil(t, resp) + + statusErr, ok := err.(StatusError) + assert.Equal(t, ok, true) + assert.Equal(t, statusErr.StatusCode, 503) + assert.Equal(t, statusErr.Message, "503 SERVICE UNAVAILABLE") +} + +func TestHTTPMock(t *testing.T) { + // TODO + type mockResponse struct { + } + + type mockClient struct { + } +} diff --git a/private/protocol/http/request.go b/private/protocol/http/request.go new file mode 100644 index 00000000..6cb5b10e --- /dev/null +++ b/private/protocol/http/request.go @@ -0,0 +1,202 @@ +package http + +import ( + "fmt" + "net/http" + "net/url" + "strings" + "time" + + "github.com/pkg/errors" + "github.com/ucloud/ucloud-sdk-go/private/utils" +) + +var avaliableHTTPMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTION", "HEAD", "PATCH"} + +type HttpRequest struct { + url string + method string + queryMap map[string]string + queryString string + headers map[string]string + + // body payload + formData map[string]string + requestBody []byte + + timeout time.Duration +} + +// NewHttpRequest will create a http request +func NewHttpRequest() HttpRequest { + return HttpRequest{ + queryMap: make(map[string]string), + headers: make(map[string]string), + formData: make(map[string]string), + timeout: DefaultTimeout, + } +} + +// SetURL will set url into request +func (h *HttpRequest) SetURL(val string) error { + // check url is valid + uri, err := url.ParseRequestURI(val) + if err != nil { + return errors.Errorf("url is invalid, got %s", val) + } + + err = h.SetQueryString(uri.RawQuery) + if err != nil { + return err + } + + h.url = val + return nil +} + +// GetURL will get request url value +func (h *HttpRequest) GetURL() string { + return h.url +} + +// SetMethod will set method of current request +func (h *HttpRequest) SetMethod(val string) error { + err := utils.CheckStringIn(val, avaliableHTTPMethods) + if err != nil { + return errors.Errorf("method is invalid, %s", err) + } + + h.method = strings.ToUpper(val) + return nil +} + +// GetMethod will get request url value +func (h *HttpRequest) GetMethod() string { + return h.method +} + +// SetQueryString will set query map by query string, +// it also save as query string attribute to keep query ordered. +func (h *HttpRequest) SetQueryString(val string) error { + // check url query is valid + values, err := url.ParseQuery(val) + if err != nil { + return errors.Errorf("url query is invalid, got %s", val) + } + + // copy url query into request query map, it will overwrite current query + for k, v := range values { + if len(v) > 0 { + h.SetQuery(k, v[0]) + } + } + + h.queryString = val + return nil +} + +// BuildQueryString will return the query string of this request, +// it will also append key-value of query map after existed query string +func (h *HttpRequest) BuildQueryString() (string, error) { + values := url.Values{} + for k, v := range h.queryMap { + values.Add(k, v) + } + + // if query string is not set by user, + // otherwise needn't keep them ordered, encode immediatly. + if h.queryString == "" { + return values.Encode(), nil + } + + // exclude query that existed in query string pass by user, + // to keep ordered from user definition + existsValues, _ := url.ParseQuery(h.queryString) + for k := range existsValues { + values.Del(k) + } + + // append query map after existed query string + qs := h.queryString + if len(values) > 0 { + qs += "&" + values.Encode() + } + + return qs, nil +} + +// SetQuery will store key-value data into query map +func (h *HttpRequest) SetQuery(k, v string) error { + if h.queryMap == nil { + h.queryMap = make(map[string]string) + } + h.queryMap[k] = v + return nil +} + +// GetQueryMap will get all of query as a map +func (h *HttpRequest) GetQueryMap() map[string]string { + return h.queryMap +} + +// SetTimeout will set timeout of current request +func (h *HttpRequest) SetTimeout(val time.Duration) error { + h.timeout = val + return nil +} + +// GetTimeout will get timeout of current request +func (h *HttpRequest) GetTimeout() time.Duration { + return h.timeout +} + +// SetHeader will set http header of current request +func (h *HttpRequest) SetHeader(k, v string) error { + if h.headers == nil { + h.headers = make(map[string]string) + } + h.headers[k] = v + return nil +} + +// GetHeaderMap wiil get all of header as a map +func (h *HttpRequest) GetHeaderMap() map[string]string { + return h.headers +} + +// SetRequestBody will set http body of current request +func (h *HttpRequest) SetRequestBody(val []byte) error { + h.requestBody = val + return nil +} + +// GetRequestBody will get origin http request ("net/http") +func (h *HttpRequest) GetRequestBody() []byte { + return h.requestBody +} + +func (h *HttpRequest) String() string { + if qs, err := h.BuildQueryString(); err == nil { + return fmt.Sprintf("%s?%s", h.GetURL(), qs) + } + return h.GetURL() +} + +func (h *HttpRequest) buildHTTPRequest() (*http.Request, error) { + qs, err := h.BuildQueryString() + if err != nil { + return nil, errors.Errorf("cannot build query string, %s", err) + } + + // NOTE: api.ucloud.cn has been supported request via form urlencoded data + url := fmt.Sprintf("%s?%s", h.GetURL(), qs) + httpReq, err := http.NewRequest(h.GetMethod(), url, nil) + if err != nil { + return nil, errors.Errorf("cannot build request, %s", err) + } + + for k, v := range utils.MergeMap(DefaultHeaders, h.GetHeaderMap()) { + httpReq.Header.Set(k, v) + } + return httpReq, nil +} diff --git a/private/protocol/http/response.go b/private/protocol/http/response.go new file mode 100644 index 00000000..1654fde3 --- /dev/null +++ b/private/protocol/http/response.go @@ -0,0 +1,38 @@ +package http + +import ( + "net/http" +) + +// HttpResponse is a simple wrapper of "net/http" response +type HttpResponse struct { + body []byte + originHttpResponse *http.Response // origin "net/http" response +} + +// NewHttpResponse will create a new response of http request +func NewHttpResponse() *HttpResponse { + return &HttpResponse{} +} + +// GetBody will get body from from sdk http request +func (h *HttpResponse) GetBody() []byte { + return h.body +} + +// GetStatusCode will return status code of origin http response +func (h *HttpResponse) GetStatusCode() int { + return h.originHttpResponse.StatusCode +} + +// setBody will set body into http response +// it usually used for restore the body already read from an stream +// it will also cause extra memory usage +func (h *HttpResponse) setBody(body []byte) error { + h.body = body + return nil +} + +func (h *HttpResponse) setHttpReponse(resp *http.Response) { + h.originHttpResponse = resp +} diff --git a/private/utils/accessor.go b/private/utils/accessor.go new file mode 100644 index 00000000..6b0e7d2c --- /dev/null +++ b/private/utils/accessor.go @@ -0,0 +1,72 @@ +package utils + +import ( + "reflect" + "strconv" + "strings" + + "github.com/pkg/errors" +) + +func ValueAtPath(v interface{}, path string) (interface{}, error) { + components := strings.Split(path, ".") + + rv := reflect.ValueOf(v) + for rv.Kind() == reflect.Ptr { + if rv.IsNil() { + return nil, errors.Errorf("object %#v is nil", v) + } + rv = rv.Elem() + } + + if rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array { + i, err := strconv.Atoi(components[0]) + if err != nil { + return nil, errors.Errorf("path %s is invalid at index of array", path) + } + + length := rv.Len() + if i >= length { + return nil, errors.Errorf("path %s is invalid, array has length %v, but got %v", path, length, i) + } + + itemV := rv.Index(i) + if !itemV.IsValid() { + return nil, errors.Errorf("path %s is invalid for map", path) + } + + if len(components) > 1 { + return ValueAtPath(itemV.Interface(), strings.Join(components[1:len(components)], ".")) + } else { + return itemV.Interface(), nil + } + } + + if rv.Kind() == reflect.Map && !rv.IsNil() { + itemV := rv.MapIndex(reflect.ValueOf(components[0])) + if !itemV.IsValid() { + return nil, errors.Errorf("path %s is invalid for map", path) + } + + if len(components) > 1 { + return ValueAtPath(itemV.Interface(), strings.Join(components[1:len(components)], ".")) + } else { + return itemV.Interface(), nil + } + } + + if rv.Kind() == reflect.Struct { + itemV := rv.FieldByName(components[0]) + if !itemV.IsValid() { + return nil, errors.Errorf("path %s is invalid for struct", path) + } + + if len(components) > 1 { + return ValueAtPath(itemV.Interface(), strings.Join(components[1:len(components)], ".")) + } else { + return itemV.Interface(), nil + } + } + + return nil, errors.Errorf("object %#v is invalid, need map or struct", v) +} diff --git a/private/utils/accessor_test.go b/private/utils/accessor_test.go new file mode 100644 index 00000000..64b6de77 --- /dev/null +++ b/private/utils/accessor_test.go @@ -0,0 +1,38 @@ +package utils + +import ( + "reflect" + "testing" +) + +func TestValueAtPath(t *testing.T) { + type args struct { + v interface{} + path string + } + tests := []struct { + name string + args args + want interface{} + wantErr bool + }{ + {"map.map", args{map[string]map[string]int{"Test": {"Name": 42}}, "Test.Name"}, 42, false}, + {"map.struct", args{map[string]struct{ Name int }{"Test": {Name: 42}}, "Test.Name"}, 42, false}, + {"struct.map", args{struct{ Test map[string]int }{Test: map[string]int{"Name": 42}}, "Test.Name"}, 42, false}, + {"struct.struct", args{struct{ Test struct{ Name int } }{Test: struct{ Name int }{Name: 42}}, "Test.Name"}, 42, false}, + {"struct.slice", args{struct{ Name []int }{[]int{42}}, "Name.0"}, 42, false}, + {"slice.struct", args{[]struct{ Name int }{struct{ Name int }{42}}, "0.Name"}, 42, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := ValueAtPath(tt.args.v, tt.args.path) + if (err != nil) != tt.wantErr { + t.Errorf("ValueAtPath() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("ValueAtPath() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/private/utils/collection.go b/private/utils/collection.go new file mode 100644 index 00000000..74fca884 --- /dev/null +++ b/private/utils/collection.go @@ -0,0 +1,43 @@ +package utils + +import ( + "fmt" + "strings" +) + +// MergeMap will merge two map and return a new map +func MergeMap(args ...map[string]string) map[string]string { + m := map[string]string{} + for _, kv := range args { + for k, v := range kv { + m[k] = v + } + } + return m +} + +// SetMapIfNotExists will set a +func SetMapIfNotExists(m map[string]string, k string, v string) { + if _, ok := m[k]; !ok && v != "" { + m[k] = v + } +} + +// IsStringIn will return if the value is contains by an array +func IsStringIn(val string, avaliables []string) bool { + for _, choice := range avaliables { + if val == choice { + return true + } + } + + return false +} + +// CheckStringIn will check if the value is contains by an array +func CheckStringIn(val string, avaliables []string) error { + if IsStringIn(val, avaliables) { + return nil + } + return fmt.Errorf("got %s, should be one of %s", val, strings.Join(avaliables, ",")) +} diff --git a/private/utils/collection_test.go b/private/utils/collection_test.go new file mode 100644 index 00000000..ab12c496 --- /dev/null +++ b/private/utils/collection_test.go @@ -0,0 +1,81 @@ +package utils + +import ( + "reflect" + "testing" +) + +func TestMergeMap(t *testing.T) { + type args struct { + args []map[string]string + } + tests := []struct { + name string + args args + want map[string]string + }{ + { + "ok", + args{ + []map[string]string{ + {"a": "1"}, + {"b": "2"}, + }, + }, + map[string]string{"a": "1", "b": "2"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := MergeMap(tt.args.args...); !reflect.DeepEqual(got, tt.want) { + t.Errorf("MergeMap() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestSetMapIfNotExists(t *testing.T) { + type args struct { + m map[string]string + k string + v string + } + tests := []struct { + name string + args args + want map[string]string + }{ + {"not_exists", args{map[string]string{"a": "1"}, "b", "2"}, map[string]string{"a": "1", "b": "2"}}, + {"not_exists", args{map[string]string{"a": "1"}, "a", "2"}, map[string]string{"a": "1"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + SetMapIfNotExists(tt.args.m, tt.args.k, tt.args.v) + if SetMapIfNotExists(tt.args.m, tt.args.k, tt.args.v); !reflect.DeepEqual(tt.args.m, tt.want) { + t.Errorf("MergeMap() = %v, want %v", tt.args.m, tt.want) + } + }) + } +} + +func TestCheckStringIn(t *testing.T) { + type args struct { + val string + avaliables []string + } + tests := []struct { + name string + args args + wantErr bool + }{ + {"ok", args{"get", []string{"get", "post"}}, false}, + {"err", args{"-", []string{"get", "post"}}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := CheckStringIn(tt.args.val, tt.args.avaliables); (err != nil) != tt.wantErr { + t.Errorf("CheckStringIn() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/private/utils/waiter.go b/private/utils/waiter.go new file mode 100644 index 00000000..e1c4152b --- /dev/null +++ b/private/utils/waiter.go @@ -0,0 +1,53 @@ +package utils + +import ( + "errors" + "time" + + "github.com/ucloud/ucloud-sdk-go/ucloud/log" +) + +// Waiter to wait sth until it completed. +type Waiter interface { + WaitForCompletion() error + Cancel() error +} + +// FuncWaiter used for waiting any condition function. +type FuncWaiter struct { + Interval time.Duration + MaxAttempts int + Checker func() (bool, error) + IgnoreError bool + + cancel chan struct{} +} + +// WaitForCompletion will wait until the state of consdition is avaliable. +// It will call the condition function to ensure state with interval. +func (w *FuncWaiter) WaitForCompletion() error { + for i := 0; ; i++ { + log.Infof("Waiting for completion ... attempted %v times, %v total", i, w.MaxAttempts) + + if i >= w.MaxAttempts { + return errors.New("maximum attemps are reached") + } + + if ok, err := w.Checker(); ok || (!w.IgnoreError && err != nil) { + return err + } + + select { + case <-time.After(w.Interval): + continue + case <-w.cancel: + break + } + } +} + +// Cancel will stop all of WaitForCompletion function call. +func (w *FuncWaiter) Cancel() error { + w.cancel <- struct{}{} + return nil +} diff --git a/private/utils/waiter_test.go b/private/utils/waiter_test.go new file mode 100644 index 00000000..e5420367 --- /dev/null +++ b/private/utils/waiter_test.go @@ -0,0 +1,71 @@ +package utils + +import ( + "testing" + "time" +) + +func TestFuncWaiter_WaitForCompletion(t *testing.T) { + tests := []struct { + name string + w *FuncWaiter + wantErr bool + }{ + { + "OK", + &FuncWaiter{ + Checker: func() func() (bool, error) { + i := 0 + return func() (bool, error) { + i++ + return i == 1, nil + } + }(), + MaxAttempts: 2, + Interval: time.Second * 1, + }, + false, + }, + { + "MaxAttempsReached", + &FuncWaiter{ + Checker: func() func() (bool, error) { + i := 0 + return func() (bool, error) { + i++ + return i == 2, nil + } + }(), + MaxAttempts: 1, + Interval: time.Second * 1, + }, + true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := tt.w.WaitForCompletion(); (err != nil) != tt.wantErr { + t.Errorf("FuncWaiter.WaitForCompletion() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestFuncWaiter_Cancel(t *testing.T) { + i := 0 + waiter := &FuncWaiter{ + Checker: func() (bool, error) { + i++ + return i == 3, nil + }, + MaxAttempts: 3, + Interval: time.Second * 1, + } + + go waiter.WaitForCompletion() + time.Sleep(time.Millisecond * 500) + + if i > 2 { + t.Errorf("FuncWaiter.Cancel() failed") + } +} diff --git a/script/example b/script/example deleted file mode 100755 index 4f42b318..00000000 --- a/script/example +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -set -e - -ARGS=$@ -if [ -z "$ARGS" ]; then - ARGS="./..." -fi - -echo $ARGS - -docker build -t goucloud . -exec docker run --rm goucloud go build ./example/uhost_example.go diff --git a/script/test b/script/test deleted file mode 100755 index d601930e..00000000 --- a/script/test +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -set -e - -ARGS=$@ -if [ -z "$ARGS" ]; then - ARGS="./..." -fi - -echo $ARGS - -docker build -t goucloud . -exec docker run --rm goucloud rm -fr ./example && go test -v -short $ARGS diff --git a/scripts/gofmtcheck.sh b/scripts/gofmtcheck.sh new file mode 100644 index 00000000..980265c2 --- /dev/null +++ b/scripts/gofmtcheck.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +# Check gofmt +echo "==> Checking that code complies with gofmt requirements..." +gofmt_files=$(find . -name '*.go' | grep -v vendor | xargs gofmt -l) +if [[ -n ${gofmt_files} ]]; then + echo 'gofmt needs running on the following files:' + echo "${gofmt_files}" + echo "You can use the command: \`make fmt\` to reformat code." + exit 1 +fi + +exit 0 diff --git a/service/udisk/api.go b/service/udisk/api.go deleted file mode 100644 index 6cb6524b..00000000 --- a/service/udisk/api.go +++ /dev/null @@ -1,74 +0,0 @@ -package udisk - -import ( - "github.com/ucloud/ucloud-sdk-go/ucloud" -) - -// CreateUDiskSnapshot params of create instances -type CreateUDiskSnapshotParams struct { - ucloud.CommonRequest - - Region string - Zone string - UDiskId string - Name string - ChargeType string - Quantity int - Comment string -} - -type CreateUDiskSnapshotResponse struct { - ucloud.CommonResponse - SnapshotId []string -} - -func (u *UDisk) CreateUDiskSnapshot(params *CreateUDiskSnapshotParams) (*CreateUDiskSnapshotResponse, error) { - response := &CreateUDiskSnapshotResponse{} - err := u.DoRequest("CreateUDiskSnapshot", params, response) - - return response, err -} - -// AttachUDiskParams params of deleting udisk -type AttachUDiskParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - UDiskId string -} - -type AttachUDiskResponse struct { - ucloud.CommonResponse - UHostId string - UDiskId string -} - -func (u *UDisk) AttachUDisk(params *AttachUDiskParams) (*AttachUDiskResponse, error) { - response := &AttachUDiskResponse{} - err := u.DoRequest("AttachUDisk", params, response) - - return response, err -} - -// DeleteUDisk params of deleting udisk -type DeleteUDiskParams struct { - ucloud.CommonRequest - - Region string - Zone string - UDiskId string -} - -type DeleteUDiskResponse struct { - ucloud.CommonResponse - SnapshotId []string -} - -func (u *UDisk) DeleteUDisk(params *DeleteUDiskParams) (*DeleteUDiskResponse, error) { - response := &DeleteUDiskResponse{} - err := u.DoRequest("DeleteUDisk", params, response) - - return response, err -} diff --git a/service/udisk/service.go b/service/udisk/service.go deleted file mode 100644 index 8d97c2e5..00000000 --- a/service/udisk/service.go +++ /dev/null @@ -1,29 +0,0 @@ -package udisk - -import ( - "net/http" - - "github.com/ucloud/ucloud-sdk-go/ucloud" - "github.com/ucloud/ucloud-sdk-go/ucloud/service" -) - -// UDisk api service for UDisk -type UDisk struct { - *service.Service -} - -// New create a uhost service -func New(config *ucloud.Config) *UDisk { - - service := &service.Service{ - Config: ucloud.DefaultConfig.Merge(config), - ServiceName: "UHost", - APIVersion: ucloud.APIVersion, - - BaseUrl: ucloud.APIBaseURL, - HttpClient: &http.Client{}, - } - - return &UDisk{service} - -} diff --git a/service/uhost/api.go b/service/uhost/api.go deleted file mode 100644 index be35b158..00000000 --- a/service/uhost/api.go +++ /dev/null @@ -1,601 +0,0 @@ -package uhost - -import ( - "github.com/ucloud/ucloud-sdk-go/ucloud" -) - -// CreateUHostInstanceParams params of create instances -type CreateUHostInstanceParams struct { - ucloud.CommonRequest - - Region string - Zone string - ImageId string - LoginMode string - Password string - KeyPair string - CPU int - Memory int - DiskSpace int - Name string - NetworkId string - SecurityGroupId string - ChargeType string - Quantity int - Count int - UHostType string - NetCapability string - Tag string - CouponId string - BootDiskSpace int -} - -type CreateUHostInstanceResponse struct { - ucloud.CommonResponse - UHostIds []string -} - -func (u *UHost) CreateUHostInstance(params *CreateUHostInstanceParams) (*CreateUHostInstanceResponse, error) { - response := &CreateUHostInstanceResponse{} - err := u.DoRequest("CreateUHostInstance", params, response) - - return response, err -} - -type DescribeUHostInstanceParams struct { - Region string - Zone string - UHostIds []string - Tag string - Offset int - Limit int -} - -type DiskSet struct { - Type string - DiskId string - Name string - Drive int - Size int -} - -type DiskSetArray []DiskSet - -type IPSet struct { - Type string - IPId string - IP string - bandwidth int -} - -type IPSetArray []IPSet - -type UHostSet struct { - UHostId string - UHostType string - Zone string - StorageType string - ImageId string - BasicImageId string - BasicImageName string - Tag string - Remark string - Name string - State string - CreateTime int - ChargeType string - ExpireTime int - CPU int - Memory int - AutoRenew string - DiskSet DiskSetArray - IPSet IPSetArray - NetCapability string - NetworkState string - TimemachineFeature string - HotplugFeature string -} - -type UHostSetArray []UHostSet - -type DescribeUHostInstanceResponse struct { - ucloud.CommonResponse - - TotalCount int - UHostSet UHostSetArray -} - -func (u *UHost) DescribeUHostInstance(params *DescribeUHostInstanceParams) (*DescribeUHostInstanceResponse, error) { - response := &DescribeUHostInstanceResponse{} - err := u.DoRequest("DescribeUHostInstance", params, response) - - return response, err -} - -type TerminateUHostInstanceParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - Destroy int -} - -type TerminateUHostInstanceResponse struct { - ucloud.CommonResponse - UhostIds []string -} - -func (u *UHost) TerminateUHostInstance(params *TerminateUHostInstanceParams) (*TerminateUHostInstanceResponse, error) { - response := &TerminateUHostInstanceResponse{} - err := u.DoRequest("TerminateUHostInstance", params, response) - - return response, err -} - -type ResizeUHostInstanceParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - CPU int - Memory int - DiskSpace int - BootDiskSpace int - NetCapValue int -} - -type ResizeUHostInstanceResponse struct { - ucloud.CommonResponse - - UHostId string -} - -func (u *UHost) ResizeUHostInstance(params *ResizeUHostInstanceParams) (*ResizeUHostInstanceResponse, error) { - response := &ResizeUHostInstanceResponse{} - err := u.DoRequest("ResizeUHostInstance", params, response) - - return response, err -} - -type ReinstallUHostInstanceParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - - Password string - ImageId string - ReserveDisk string -} - -type ReinstallUHostInstanceResponse struct { - ucloud.CommonResponse - - UHostId string -} - -func (u *UHost) ReinstallUHostInstance(params *ReinstallUHostInstanceParams) (*ReinstallUHostInstanceResponse, error) { - response := &ReinstallUHostInstanceResponse{} - err := u.DoRequest("ReinstallUHostInstance", params, response) - - return response, err -} - -type StartUHostInstanceParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string -} - -type StartUHostInstanceResponse struct { - ucloud.CommonResponse - UhostId string -} - -func (u *UHost) StartUHostInstance(params *StartUHostInstanceParams) (*StartUHostInstanceResponse, error) { - response := &StartUHostInstanceResponse{} - err := u.DoRequest("StartUHostInstance", params, response) - - return response, err -} - -type StopUHostInstanceParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string -} - -type StopUHostInstanceResponse struct { - ucloud.CommonResponse - - UhostId string -} - -func (u *UHost) StopUHostInstance(params *StopUHostInstanceParams) (*StopUHostInstanceResponse, error) { - response := &StopUHostInstanceResponse{} - err := u.DoRequest("StopUHostInstance", params, response) - - return response, err -} - -type PoweroffUHostInstanceParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string -} - -type PoweroffUHostInstanceResponse struct { - ucloud.CommonResponse - - UhostId string -} - -func (u *UHost) PoweroffUHostInstance(params *PoweroffUHostInstanceParams) (*PoweroffUHostInstanceResponse, error) { - response := &PoweroffUHostInstanceResponse{} - err := u.DoRequest("PoweroffUHostInstance", params, response) - - return response, err -} - -type RebootUHostInstanceParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string -} - -type RebootUHostInstanceResponse struct { - ucloud.CommonResponse - - UhostId string -} - -func (u *UHost) RebootUHostInstance(params *RebootUHostInstanceParams) (*RebootUHostInstanceResponse, error) { - response := &RebootUHostInstanceResponse{} - err := u.DoRequest("RebootUHostInstance", params, response) - - return response, err -} - -type ResetUHostInstancePasswordParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - Password string -} - -type ResetUHostInstancePasswordResponse struct { - ucloud.CommonResponse - - UhostId string -} - -func (u *UHost) ResetUHostInstancePassword(params *ResetUHostInstancePasswordParams) (*ResetUHostInstancePasswordResponse, error) { - response := &ResetUHostInstancePasswordResponse{} - err := u.DoRequest("ResetUHostInstancePassword", params, response) - - return response, err -} - -type ModifyUHostInstanceNameParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - Name string -} - -type ModifyUHostInstanceNameResponse struct { - ucloud.CommonResponse - - UHostId string -} - -func (u *UHost) ModifyUHostInstanceName(params *ModifyUHostInstanceNameParams) (*ModifyUHostInstanceNameResponse, error) { - response := &ModifyUHostInstanceNameResponse{} - err := u.DoRequest("ModifyUHostInstanceName", params, response) - - return response, err -} - -type ModifyUHostInstanceTagParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - Tag string -} - -type ModifyUHostInstanceTagResponse struct { - ucloud.CommonResponse - - UHostId string -} - -func (u *UHost) ModifyUHostInstanceTag(params *ModifyUHostInstanceTagParams) (*ModifyUHostInstanceTagResponse, error) { - response := &ModifyUHostInstanceTagResponse{} - err := u.DoRequest("ModifyUHostInstanceTag", params, response) - - return response, err -} - -type ModifyUHostInstanceRemarkParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - Remark string -} - -type ModifyUHostInstanceRemarkResponse struct { - ucloud.CommonResponse - - UHostId string -} - -func (u *UHost) ModifyUHostInstanceRemark(params *ModifyUHostInstanceRemarkParams) (*ModifyUHostInstanceRemarkResponse, error) { - response := &ModifyUHostInstanceRemarkResponse{} - err := u.DoRequest("ModifyUHostInstanceRemark", params, response) - - return response, err -} - -type GetUHostInstancePriceParams struct { - ucloud.CommonRequest - - Region string - Zone string - ImageId string - CPU int - Memory int - Count int - ChargeType string - StorageType string - DiskSpace int - UHostType string - NetCapability string - TimemachineFeature string -} - -type PriceSet struct { - ChargeType string - Price float64 -} - -type GetUHostInstancePriceResponse struct { - ucloud.CommonResponse - - UHostId string - PriceSet []PriceSet -} - -func (u *UHost) GetUHostInstancePrice(params *GetUHostInstancePriceParams) (*GetUHostInstancePriceResponse, error) { - response := &GetUHostInstancePriceResponse{} - err := u.DoRequest("GetUHostInstancePrice", params, response) - - return response, err -} - -type GetUHostInstanceVncInfoParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string -} - -type GetUHostInstanceVncInfoResponse struct { - ucloud.CommonResponse - - UHostId string - VncIP string - VncPort int - VncPassword string -} - -func (u *UHost) GetUHostInstanceVncInfo(params *GetUHostInstanceVncInfoParams) (*GetUHostInstanceVncInfoResponse, error) { - response := &GetUHostInstanceVncInfoResponse{} - err := u.DoRequest("GetUHostInstanceVncInfo", params, response) - - return response, err -} - -type DescribeImageParams struct { - ucloud.CommonRequest - - Region string - Zone string - ImageType string - OsType string - ImageId string - Offset int - Limit int -} - -type ImageSet struct { - ImageId string - ImageName string - Zone string - OsType string - OsName string - ImageType string - Features []string - FuncType string - IntegratedSoftware string - Vendor string - Links string - State string - ImageDescription string - CreateTime int - ImageSize int -} - -type ImageSetArray []ImageSet - -type DescribeImageResponse struct { - ucloud.CommonResponse - - TotalCount int - ImageSet ImageSetArray -} - -func (u *UHost) DescribeImage(params *DescribeImageParams) (*DescribeImageResponse, error) { - response := &DescribeImageResponse{} - err := u.DoRequest("DescribeImage", params, response) - - return response, err -} - -type CreateCustomImageParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - ImageName string - ImageDescription string -} - -type CreateCustomImageResponse struct { - ucloud.CommonResponse - - ImageId string -} - -func (u *UHost) CreateCustomImage(params *CreateCustomImageParams) (*CreateCustomImageResponse, error) { - response := &CreateCustomImageResponse{} - err := u.DoRequest("CreateCustomImage", params, response) - - return response, err -} - -type TerminateCustomImageParams struct { - ucloud.CommonRequest - - Region string - Zone string - ImageId string -} - -type TerminateCustomImageResponse struct { - ucloud.CommonResponse - - ImageId string -} - -func (u *UHost) TerminateCustomImage(params *TerminateCustomImageParams) (*TerminateCustomImageResponse, error) { - response := &TerminateCustomImageResponse{} - err := u.DoRequest("TerminateCustomImage", params, response) - - return response, err -} - -type AttachUDiskParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - UDiskId string -} - -type AttachUDiskResponse struct { - ucloud.CommonResponse - - UHostId string - UDiskId string -} - -func (u *UHost) AttachUDisk(params *AttachUDiskParams) (*AttachUDiskResponse, error) { - response := &AttachUDiskResponse{} - err := u.DoRequest("AttachUDisk", params, response) - - return response, err -} - -type DetachUDiskParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string - UDiskId string -} - -type DetachUDiskResponse struct { - ucloud.CommonResponse - - UHostId string - UDiskId string -} - -func (u *UHost) DetachUDisk(params *DetachUDiskParams) (*DetachUDiskResponse, error) { - response := &DetachUDiskResponse{} - err := u.DoRequest("DetachUDisk", params, response) - - return response, err -} - -type CreateUHostInstanceSnapshotParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string -} - -type CreateUHostInstanceSnapshotResponse struct { - ucloud.CommonResponse - - UHostId string - SnapshotName string -} - -func (u *UHost) CreateUHostInstanceSnapshot(params *CreateUHostInstanceSnapshotParams) (*CreateUHostInstanceSnapshotResponse, error) { - response := &CreateUHostInstanceSnapshotResponse{} - err := u.DoRequest("CreateUHostInstanceSnapshot", params, response) - - return response, err -} - -type DescribeUHostInstanceSnapshotParams struct { - ucloud.CommonRequest - - Region string - Zone string - UHostId string -} - -type SnapshotSet struct { - SnapshotName string - SnapshotTime string -} - -type DescribeUHostInstanceSnapshotResponse struct { - ucloud.CommonResponse - - UHostId string - SnapshotSet []SnapshotSet -} - -func (u *UHost) DescribeUHostInstanceSnapshot(params *DescribeUHostInstanceSnapshotParams) (*DescribeUHostInstanceSnapshotResponse, error) { - response := &DescribeUHostInstanceSnapshotResponse{} - err := u.DoRequest("DescribeUHostInstanceSnapshot", params, response) - - return response, err -} diff --git a/service/uhost/service.go b/service/uhost/service.go deleted file mode 100644 index 7da954a6..00000000 --- a/service/uhost/service.go +++ /dev/null @@ -1,29 +0,0 @@ -package uhost - -import ( - "net/http" - - "github.com/ucloud/ucloud-sdk-go/ucloud" - "github.com/ucloud/ucloud-sdk-go/ucloud/service" -) - -// UHost api service for UHost -type UHost struct { - *service.Service -} - -// New create a uhost service -func New(config *ucloud.Config) *UHost { - - service := &service.Service{ - Config: ucloud.DefaultConfig.Merge(config), - ServiceName: "UHost", - APIVersion: ucloud.APIVersion, - - BaseUrl: ucloud.APIBaseURL, - HttpClient: &http.Client{}, - } - - return &UHost{service} - -} diff --git a/service/unet/api.go b/service/unet/api.go deleted file mode 100644 index 619e1713..00000000 --- a/service/unet/api.go +++ /dev/null @@ -1,723 +0,0 @@ -package unet - -import ( - "github.com/ucloud/ucloud-sdk-go/ucloud" -) - -type AllocateEIPParams struct { - ucloud.CommonRequest - - OperatorName string - Region string - Bandwidth int - Tag string - ChargeType string - Quantity int - PayMode string - ShareBandwidthId string - CouponId string - Name string - Remark string -} - -type EIPAddr struct { - OperatorName string - IP string -} - -type ShareBandwidthSet struct { - ShareBandwidth int - ShareBandwidthId string - ShareBandwidthName string -} - -type EIPSet struct { - EIPId string - CurBandwidth float32 - Weight int - BandwidthType int - Bandwidth int - Status string - ChargeType string - CreateTime int - ExpireTime int - Name string - Tag string - Remark string - PayMode string - ShareBandwidthSet *ShareBandwidthSet - EIPAddr *[]EIPAddr - Resource *[]ucloud.Resource -} - -type AllocateEIPResponse struct { - ucloud.CommonResponse - - EIPSet *[]EIPSet -} - -func (u *UNet) AllocateEIP(params *AllocateEIPParams) (*AllocateEIPResponse, error) { - response := &AllocateEIPResponse{} - err := u.DoRequest("AllocateEIP", params, response) - - return response, err -} - -type DescribeEIPParams struct { - ucloud.CommonRequest - - Region string - EIPIds []string - OffSet int - Limit int -} - -type DescribeEIPResponse struct { - ucloud.CommonResponse - - TotalCount int - TotalBandwidth int - EIPSet *[]EIPSet -} - -func (u *UNet) DescribeEIP(params *DescribeEIPParams) (*DescribeEIPResponse, error) { - response := &DescribeEIPResponse{} - err := u.DoRequest("DescribeEIP", params, response) - - return response, err -} - -type UpdateEIPAttributeParams struct { - ucloud.CommonRequest - - Region string - EIPId string - Name string - Tag string - Remark string -} - -type UpdateEIPAttributeResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) UpdateEIPAttribute(params *UpdateEIPAttributeParams) (*UpdateEIPAttributeResponse, error) { - response := &UpdateEIPAttributeResponse{} - err := u.DoRequest("UpdateEIPAttribute", params, response) - - return response, err -} - -type ReleaseEIPParams struct { - ucloud.CommonRequest - - Region string - EIPId string -} - -type ReleaseEIPResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) ReleaseEIP(params *ReleaseEIPParams) (*ReleaseEIPResponse, error) { - response := &ReleaseEIPResponse{} - err := u.DoRequest("ReleaseEIP", params, response) - - return response, err -} - -type BindEIPParams struct { - ucloud.CommonRequest - - Region string - EIPId string - ResourceType string - ResourceId string -} - -type BindEIPResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) BindEIP(params *BindEIPParams) (*BindEIPResponse, error) { - response := &BindEIPResponse{} - err := u.DoRequest("BindEIP", params, response) - - return response, err -} - -type UnBindEIPParams struct { - ucloud.CommonRequest - - Region string - EIPId string - ResourceType string - ResourceId string -} - -type UnBindEIPResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) UnBindEIP(params *UnBindEIPParams) (*UnBindEIPResponse, error) { - response := &UnBindEIPResponse{} - err := u.DoRequest("UnBindEIP", params, response) - - return response, err -} - -type ModifyEIPBandwidthParams struct { - ucloud.CommonRequest - - Region string - EIPId string - Bandwidth int -} - -type ModifyEIPBandwidthResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) ModifyEIPBandwidth(params *ModifyEIPBandwidthParams) (*ModifyEIPBandwidthResponse, error) { - response := &ModifyEIPBandwidthResponse{} - err := u.DoRequest("ModifyEIPBandwidth", params, response) - - return response, err -} - -type ModifyEIPWeightParams struct { - ucloud.CommonRequest - - Region string - EIPId string - Weight int -} - -type ModifyEIPWeightResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) ModifyEIPWeight(params *ModifyEIPWeightParams) (*ModifyEIPWeightResponse, error) { - response := &ModifyEIPWeightResponse{} - err := u.DoRequest("ModifyEIPWeight", params, response) - - return response, err -} - -type GetEIPPriceParams struct { - ucloud.CommonRequest - - OperatorName string - Bandwidth int - ChargeType string - PayMode string -} - -type PriceSet struct { - ChargeType string - Price float32 - PurchaseValue int -} -type GetEIPPriceResponse struct { - ucloud.CommonResponse - - PriceSet *[]PriceSet -} - -func (u *UNet) GetEIPPrice(params *GetEIPPriceParams) (*GetEIPPriceResponse, error) { - response := &GetEIPPriceResponse{} - err := u.DoRequest("GetEIPPrice", params, response) - - return response, err -} - -type GetEIPUpgradePriceParams struct { - ucloud.CommonRequest - - Region string - EIPId string - Bandwidth int -} - -type GetEIPUpgradePriceResponse struct { - ucloud.CommonResponse - - Price float64 -} - -func (u *UNet) GetEIPUpgradePrice(params *GetEIPUpgradePriceParams) (*GetEIPUpgradePriceResponse, error) { - response := &GetEIPUpgradePriceResponse{} - err := u.DoRequest("GetEIPUpgradePrice", params, response) - - return response, err -} - -type GetEIPPayModeEIPParams struct { - ucloud.CommonRequest - - Region string - EIPIds []string -} - -type EIPPayMode struct { - EIPId string - EIPPaymode string -} - -type GetEIPPayModeEIPResponse struct { - ucloud.CommonResponse - - EIPPayMode *[]EIPPayMode -} - -func (u *UNet) GetEIPPayModeEIP(params *GetEIPUpgradePriceParams) (*GetEIPPayModeEIPResponse, error) { - response := &GetEIPPayModeEIPResponse{} - err := u.DoRequest("GetEIPPayModeEIP", params, response) - - return response, err -} - -type SetEIPPayModeParams struct { - ucloud.CommonRequest - - Region string - EIPId string - Bandwidth int - PayMode string -} - -type SetEIPPayModeResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) SetEIPPayMode(params *SetEIPPayModeParams) (*SetEIPPayModeResponse, error) { - response := &SetEIPPayModeResponse{} - err := u.DoRequest("SetEIPPayMode", params, response) - - return response, err -} - -type CreateSecurityGroupParams struct { - ucloud.CommonRequest - - Region string - GroupName string - Description string - Rule []string -} - -type CreateSecurityGroupResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) CreateSecurityGroup(params *CreateSecurityGroupParams) (*CreateSecurityGroupResponse, error) { - response := &CreateSecurityGroupResponse{} - err := u.DoRequest("CreateSecurityGroup", params, response) - - return response, err -} - -type DescribeSecurityGroupParams struct { - ucloud.CommonRequest - - Region string - ResourceType string - ResourceId int - GroupId string -} - -type Rule struct { - SrcIP string - Priority int - ProtocolType string - DstPort string - RuleAction string -} - -type FirewallDataSet struct { - GroupId int - GroupName string - CreateTime int - Type int - Description string - Rule *[]Rule -} - -type DescribeSecurityGroupResponse struct { - ucloud.CommonResponse - - DataSet []FirewallDataSet -} - -func (u *UNet) DescribeSecurityGroup(params *DescribeSecurityGroupParams) (*DescribeSecurityGroupResponse, error) { - response := &DescribeSecurityGroupResponse{} - err := u.DoRequest("DescribeSecurityGroup", params, response) - - return response, err -} - -type DescribeSecurityGroupResourceParams struct { - ucloud.CommonRequest - - Region string - GroupId int -} - -type DescribeSecurityGroupResourceResponse struct { - ucloud.CommonResponse - - DataSet []string -} - -func (u *UNet) DescribeSecurityGroupResource(params *DescribeSecurityGroupParams) (*DescribeSecurityGroupResourceResponse, error) { - response := &DescribeSecurityGroupResourceResponse{} - err := u.DoRequest("DescribeSecurityGroupResource", params, response) - - return response, err -} - -type UpdateSecurityGroupParams struct { - ucloud.CommonRequest - - Region string - GroupId int - Rule []string -} - -type UpdateSecurityGroupResponse struct { - ucloud.CommonResponse - - DataSet []string -} - -func (u *UNet) UpdateSecurityGroup(params *UpdateSecurityGroupParams) (*UpdateSecurityGroupResponse, error) { - response := &UpdateSecurityGroupResponse{} - err := u.DoRequest("UpdateSecurityGroup", params, response) - - return response, err -} - -type GrantSecurityGroupParams struct { - ucloud.CommonRequest - - Region string - GroupId int - ResourceType string - ResourceId string -} - -type GrantSecurityGroupResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) GrantSecurityGroup(params *GrantSecurityGroupParams) (*GrantSecurityGroupResponse, error) { - response := &GrantSecurityGroupResponse{} - err := u.DoRequest("GrantSecurityGroup", params, response) - - return response, err -} - -type DeleteSecurityGroupParams struct { - ucloud.CommonRequest - - Region string - GroupId int -} - -type DeleteSecurityGroupResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) DeleteSecurityGroup(params *DeleteSecurityGroupParams) (*DeleteSecurityGroupResponse, error) { - response := &DeleteSecurityGroupResponse{} - err := u.DoRequest("DeleteSecurityGroup", params, response) - - return response, err -} - -type AllocateVIPParams struct { - ucloud.CommonRequest - - Region string - Zone string - Count int -} - -type AllocateVIPResponse struct { - ucloud.CommonResponse - - DataSet []string -} - -func (u *UNet) AllocateVIP(params *AllocateVIPParams) (*AllocateVIPResponse, error) { - response := &AllocateVIPResponse{} - err := u.DoRequest("AllocateVIP", params, response) - - return response, err -} - -type DescribeVIPParams struct { - ucloud.CommonRequest - - Region string - Zone string -} - -type DescribeVIPResponse struct { - ucloud.CommonResponse - - DataSet []string -} - -func (u *UNet) DescribeVIP(params *DescribeVIPParams) (*DescribeVIPResponse, error) { - response := &DescribeVIPResponse{} - err := u.DoRequest("DescribeVIP", params, response) - - return response, err -} - -type ReleaseVIPParams struct { - ucloud.CommonRequest - - Region string - Zone string - VIP string -} - -type ReleaseVIPResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) ReleaseVIP(params *ReleaseVIPParams) (*ReleaseVIPResponse, error) { - response := &ReleaseVIPResponse{} - err := u.DoRequest("ReleaseVIP", params, response) - - return response, err -} - -type CreateBandwidthPackageParams struct { - ucloud.CommonRequest - - Region string - EIPId string - Bandwidth int - EnableTime int - TimeRange int - CouponId string -} - -type CreateBandwidthPackageResponse struct { - ucloud.CommonResponse - - BandwidthPackageId string -} - -func (u *UNet) CreateBandwidthPackage(params *CreateBandwidthPackageParams) (*CreateBandwidthPackageResponse, error) { - response := &CreateBandwidthPackageResponse{} - err := u.DoRequest("CreateBandwidthPackage", params, response) - - return response, err -} - -type DescribeBandwidthPackageParams struct { - ucloud.CommonRequest - - Region string - Limit int - OffSet int -} - -type BandwidthPackageDataSet struct { - BandwidthPackageId string - EnableTime int - DisableTime int - CreateTime int - Bandwidth int - EIPId string - EIPAddr *[]EIPAddr -} - -type DescribeBandwidthPackageResponse struct { - ucloud.CommonResponse - - TotalCount int - DataSets *[]BandwidthPackageDataSet -} - -func (u *UNet) DescribeBandwidthPackage(params *DescribeBandwidthPackageParams) (*DescribeBandwidthPackageResponse, error) { - response := &DescribeBandwidthPackageResponse{} - err := u.DoRequest("DescribeBandwidthPackage", params, response) - - return response, err -} - -type DeleteBandwidthPackageParams struct { - ucloud.CommonRequest - - Region string - BandwidthPackageId string -} - -type DeleteBandwidthPackageResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) DeleteBandwidthPackage(params *DeleteBandwidthPackageParams) (*DeleteBandwidthPackageResponse, error) { - response := &DeleteBandwidthPackageResponse{} - err := u.DoRequest("DeleteBandwidthPackage", params, response) - - return response, err -} - -type AllocateShareBandwidthParams struct { - ucloud.CommonRequest - - Region string - ShareBandwidth int - ChargeType string - Quantity int - Name string -} - -type AllocateShareBandwidthResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) AllocateShareBandwidth(params *AllocateShareBandwidthParams) (*AllocateShareBandwidthResponse, error) { - response := &AllocateShareBandwidthResponse{} - err := u.DoRequest("AllocateShareBandwidth", params, response) - - return response, err -} - -type DescribeShareBandwidthParams struct { - ucloud.CommonRequest - - Region string - ShareBandwidthIds []string -} - -type UNetShareBandwidthSet struct { - Bandwidth int - ShareBandwidthId string - ChargeType string - CreateTime int - ExpireTime int - EIPSet *[]EIPAddr -} - -type DescribeShareBandwidthResponse struct { - ucloud.CommonResponse - - DataSet *[]UNetShareBandwidthSet -} - -func (u *UNet) DescribeShareBandwidth(params *DescribeShareBandwidthParams) (*DescribeShareBandwidthResponse, error) { - response := &DescribeShareBandwidthResponse{} - err := u.DoRequest("DescribeShareBandwidth", params, response) - - return response, err -} - -type ResizeShareBandwidthParams struct { - ucloud.CommonRequest - - Region string - ShareBandwidth int - ShareBandwidthId string -} - -type ResizeShareBandwidthResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) ResizeShareBandwidth(params *ResizeShareBandwidthParams) (*ResizeShareBandwidthResponse, error) { - response := &ResizeShareBandwidthResponse{} - err := u.DoRequest("ResizeShareBandwidth", params, response) - - return response, err -} - -type ReleaseShareBandwidthParams struct { - ucloud.CommonRequest - - Region string - EIPBandwidth int - ShareBandwidthId string -} - -type ReleaseShareBandwidthResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) ReleaseShareBandwidth(params *ReleaseShareBandwidthParams) (*ReleaseShareBandwidthResponse, error) { - response := &ReleaseShareBandwidthResponse{} - err := u.DoRequest("ReleaseShareBandwidth", params, response) - - return response, err -} - -type AssociateEIPWithShareBandwidthParams struct { - ucloud.CommonRequest - - Region string - EIPIds []string - ShareBandwidthId string -} - -type AssociateEIPWithShareBandwidthResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) AssociateEIPWithShareBandwidth(params *AssociateEIPWithShareBandwidthParams) (*AssociateEIPWithShareBandwidthResponse, error) { - response := &AssociateEIPWithShareBandwidthResponse{} - err := u.DoRequest("AssociateEIPWithShareBandwidth", params, response) - - return response, err -} - -type DisassociateEIPWithShareBandwidthParams struct { - ucloud.CommonRequest - - Region string - EIPIds []string - ShareBandwidthId string - Bandwidth int -} - -type DisassociateEIPWithShareBandwidthResponse struct { - ucloud.CommonResponse -} - -func (u *UNet) DisassociateEIPWithShareBandwidth(params *DisassociateEIPWithShareBandwidthParams) (*DisassociateEIPWithShareBandwidthResponse, error) { - response := &DisassociateEIPWithShareBandwidthResponse{} - err := u.DoRequest("DisassociateEIPWithShareBandwidth", params, response) - - return response, err -} - -type DescribeBandwidthUsageParams struct { - ucloud.CommonRequest - - OffSet int - Limit int - EIPIds []string -} - -type UnetBandwidthUsageEIPSet struct { - CurBandwidth float64 - EIPId string -} -type DescribeBandwidthUsageResponse struct { - ucloud.CommonResponse - - TotalCount int - EIPSet *[]UnetBandwidthUsageEIPSet -} - -func (u *UNet) DescribeBandwidthUsage(params *ResizeShareBandwidthParams) (*ResizeShareBandwidthResponse, error) { - response := &ResizeShareBandwidthResponse{} - err := u.DoRequest("DescribeBandwidthUsage", params, response) - - return response, err -} diff --git a/service/unet/service.go b/service/unet/service.go deleted file mode 100644 index 7b526d4e..00000000 --- a/service/unet/service.go +++ /dev/null @@ -1,27 +0,0 @@ -package unet - -import ( - "net/http" - - "github.com/ucloud/ucloud-sdk-go/ucloud" - "github.com/ucloud/ucloud-sdk-go/ucloud/service" -) - -type UNet struct { - *service.Service -} - -func New(config *ucloud.Config) *UNet { - - service := &service.Service{ - Config: ucloud.DefaultConfig.Merge(config), - ServiceName: "UNet", - APIVersion: ucloud.APIVersion, - - BaseUrl: ucloud.APIBaseURL, - HttpClient: &http.Client{}, - } - - return &UNet{service} - -} diff --git a/services/client.go b/services/client.go new file mode 100644 index 00000000..eb12b9d6 --- /dev/null +++ b/services/client.go @@ -0,0 +1,43 @@ +package services + +import ( + "github.com/ucloud/ucloud-sdk-go/services/pathx" + "github.com/ucloud/ucloud-sdk-go/services/uaccount" + "github.com/ucloud/ucloud-sdk-go/services/uhost" + "github.com/ucloud/ucloud-sdk-go/services/ulb" + "github.com/ucloud/ucloud-sdk-go/services/unet" + "github.com/ucloud/ucloud-sdk-go/services/vpc" + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type Client struct { + uaccount.UAccountClient + + uhost.UHostClient + + unet.UNetClient + + ulb.ULBClient + + vpc.VPCClient + + pathx.PathXClient +} + +// NewClient will return a aggregate client +func NewClient(config *ucloud.Config, credential *auth.Credential) *Client { + return &Client{ + *uaccount.NewClient(config, credential), + + *uhost.NewClient(config, credential), + + *unet.NewClient(config, credential), + + *ulb.NewClient(config, credential), + + *vpc.NewClient(config, credential), + + *pathx.NewClient(config, credential), + } +} diff --git a/services/pathx/client.go b/services/pathx/client.go new file mode 100644 index 00000000..91e4b387 --- /dev/null +++ b/services/pathx/client.go @@ -0,0 +1,17 @@ +package pathx + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type PathXClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *PathXClient { + client := ucloud.NewClient(config, credential) + return &PathXClient{ + client: client, + } +} diff --git a/services/pathx/create_global_sshinstance.go b/services/pathx/create_global_sshinstance.go new file mode 100644 index 00000000..651c86f3 --- /dev/null +++ b/services/pathx/create_global_sshinstance.go @@ -0,0 +1,77 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api PathX CreateGlobalSSHInstance + +package pathx + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateGlobalSSHInstanceRequest is request schema for CreateGlobalSSHInstance action +type CreateGlobalSSHInstanceRequest struct { + request.CommonBase + + // 填写支持SSH访问IP的地区名称,如“洛杉矶”,“新加坡”,“香港”,“东京”,“华盛顿”,“法兰克福”。Area和AreaCode两者必填一个 + Area *string `required:"true"` + + // 被SSH访问的IP + TargetIP *string `required:"true"` + + // SSH端口,1-65535且不能使用80,443端口 + Port *int `required:"true"` + + // AreaCode, 区域航空港国际通用代码。Area和AreaCode两者必填一个 + AreaCode *string `required:"true"` + + // 备注信息 + Remark *string `required:"false"` + + // 支付方式,如按月、按年、按时 + ChargeType *string `required:"false"` + + // 购买数量 + Quantity *int `required:"false"` + + // 使用代金券可冲抵部分费用 + CouponId *string `required:"false"` +} + +// CreateGlobalSSHInstanceResponse is response schema for CreateGlobalSSHInstance action +type CreateGlobalSSHInstanceResponse struct { + response.CommonBase + + // 实例ID,资源唯一标识 + InstanceId string + + // 加速域名,访问该域名可就近接入 + AcceleratingDomain string + + // 提示信息 + Message string +} + +// NewCreateGlobalSSHInstanceRequest will create request of CreateGlobalSSHInstance action. +func (c *PathXClient) NewCreateGlobalSSHInstanceRequest() *CreateGlobalSSHInstanceRequest { + req := &CreateGlobalSSHInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateGlobalSSHInstance - 创建GlobalSSH实例 +func (c *PathXClient) CreateGlobalSSHInstance(req *CreateGlobalSSHInstanceRequest) (*CreateGlobalSSHInstanceResponse, error) { + var err error + var res CreateGlobalSSHInstanceResponse + + err = c.client.InvokeAction("CreateGlobalSSHInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/pathx/delete_global_sshinstance.go b/services/pathx/delete_global_sshinstance.go new file mode 100644 index 00000000..14b181f8 --- /dev/null +++ b/services/pathx/delete_global_sshinstance.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api PathX DeleteGlobalSSHInstance + +package pathx + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeleteGlobalSSHInstanceRequest is request schema for DeleteGlobalSSHInstance action +type DeleteGlobalSSHInstanceRequest struct { + request.CommonBase + + // 实例Id,资源的唯一标识 + InstanceId *string `required:"true"` +} + +// DeleteGlobalSSHInstanceResponse is response schema for DeleteGlobalSSHInstance action +type DeleteGlobalSSHInstanceResponse struct { + response.CommonBase + + // 提示信息 + Message string +} + +// NewDeleteGlobalSSHInstanceRequest will create request of DeleteGlobalSSHInstance action. +func (c *PathXClient) NewDeleteGlobalSSHInstanceRequest() *DeleteGlobalSSHInstanceRequest { + req := &DeleteGlobalSSHInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DeleteGlobalSSHInstance - 删除GlobalSSH实例 +func (c *PathXClient) DeleteGlobalSSHInstance(req *DeleteGlobalSSHInstanceRequest) (*DeleteGlobalSSHInstanceResponse, error) { + var err error + var res DeleteGlobalSSHInstanceResponse + + err = c.client.InvokeAction("DeleteGlobalSSHInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/pathx/describe_global_ssharea.go b/services/pathx/describe_global_ssharea.go new file mode 100644 index 00000000..1695a82a --- /dev/null +++ b/services/pathx/describe_global_ssharea.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api PathX DescribeGlobalSSHArea + +package pathx + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeGlobalSSHAreaRequest is request schema for DescribeGlobalSSHArea action +type DescribeGlobalSSHAreaRequest struct { + request.CommonBase +} + +// DescribeGlobalSSHAreaResponse is response schema for DescribeGlobalSSHArea action +type DescribeGlobalSSHAreaResponse struct { + response.CommonBase + + // 支持GlobalSSH的地区 + AreaSet []GlobalSSHArea + + // 提示信息 + Message string +} + +// NewDescribeGlobalSSHAreaRequest will create request of DescribeGlobalSSHArea action. +func (c *PathXClient) NewDescribeGlobalSSHAreaRequest() *DescribeGlobalSSHAreaRequest { + req := &DescribeGlobalSSHAreaRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeGlobalSSHArea - 获取GlobalSSH覆盖的地区列表 用于控制显示哪些机房地域可以使用SSH特性 +func (c *PathXClient) DescribeGlobalSSHArea(req *DescribeGlobalSSHAreaRequest) (*DescribeGlobalSSHAreaResponse, error) { + var err error + var res DescribeGlobalSSHAreaResponse + + err = c.client.InvokeAction("DescribeGlobalSSHArea", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/pathx/describe_global_sshinstance.go b/services/pathx/describe_global_sshinstance.go new file mode 100644 index 00000000..97c198ee --- /dev/null +++ b/services/pathx/describe_global_sshinstance.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api PathX DescribeGlobalSSHInstance + +package pathx + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeGlobalSSHInstanceRequest is request schema for DescribeGlobalSSHInstance action +type DescribeGlobalSSHInstanceRequest struct { + request.CommonBase + + // 实例ID,资源唯一标识 + InstanceId *string `required:"false"` +} + +// DescribeGlobalSSHInstanceResponse is response schema for DescribeGlobalSSHInstance action +type DescribeGlobalSSHInstanceResponse struct { + response.CommonBase + + // GlobalSSH实例列表,实例的属性参考GlobalSSHInfo模型 + InstanceSet []GlobalSSHInfo +} + +// NewDescribeGlobalSSHInstanceRequest will create request of DescribeGlobalSSHInstance action. +func (c *PathXClient) NewDescribeGlobalSSHInstanceRequest() *DescribeGlobalSSHInstanceRequest { + req := &DescribeGlobalSSHInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeGlobalSSHInstance - 获取GlobalSSH实例列表(传实例ID获取单个实例信息,不传获取项目下全部实例) +func (c *PathXClient) DescribeGlobalSSHInstance(req *DescribeGlobalSSHInstanceRequest) (*DescribeGlobalSSHInstanceResponse, error) { + var err error + var res DescribeGlobalSSHInstanceResponse + + err = c.client.InvokeAction("DescribeGlobalSSHInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/pathx/doc.go b/services/pathx/doc.go new file mode 100644 index 00000000..3ed3fc69 --- /dev/null +++ b/services/pathx/doc.go @@ -0,0 +1,11 @@ +/* + Package uhost include resources of ucloud host product + + See also + + - API: https://docs.ucloud.cn/api/pathx-api/index + - Product: https://www.ucloud.cn/site/product/pathx.html + + for detail. +*/ +package pathx diff --git a/services/pathx/modify_global_sshport.go b/services/pathx/modify_global_sshport.go new file mode 100644 index 00000000..8a2cd616 --- /dev/null +++ b/services/pathx/modify_global_sshport.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api PathX ModifyGlobalSSHPort + +package pathx + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ModifyGlobalSSHPortRequest is request schema for ModifyGlobalSSHPort action +type ModifyGlobalSSHPortRequest struct { + request.CommonBase + + // 实例ID,资源唯一标识 + InstanceId *string `required:"true"` + + // 调整后的SSH登陆端口 + Port *int `required:"true"` +} + +// ModifyGlobalSSHPortResponse is response schema for ModifyGlobalSSHPort action +type ModifyGlobalSSHPortResponse struct { + response.CommonBase + + // 提示信息 + Message string +} + +// NewModifyGlobalSSHPortRequest will create request of ModifyGlobalSSHPort action. +func (c *PathXClient) NewModifyGlobalSSHPortRequest() *ModifyGlobalSSHPortRequest { + req := &ModifyGlobalSSHPortRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ModifyGlobalSSHPort - 修改GlobalSSH端口 +func (c *PathXClient) ModifyGlobalSSHPort(req *ModifyGlobalSSHPortRequest) (*ModifyGlobalSSHPortResponse, error) { + var err error + var res ModifyGlobalSSHPortResponse + + err = c.client.InvokeAction("ModifyGlobalSSHPort", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/pathx/modify_global_sshremark.go b/services/pathx/modify_global_sshremark.go new file mode 100644 index 00000000..d9fbc8b9 --- /dev/null +++ b/services/pathx/modify_global_sshremark.go @@ -0,0 +1,48 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api PathX ModifyGlobalSSHRemark + +package pathx + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ModifyGlobalSSHRemarkRequest is request schema for ModifyGlobalSSHRemark action +type ModifyGlobalSSHRemarkRequest struct { + request.CommonBase + + // 实例ID,资源唯一标识 + InstanceId *string `required:"true"` + + // 备注信息,不填默认为空字符串 + Remark *string `required:"false"` +} + +// ModifyGlobalSSHRemarkResponse is response schema for ModifyGlobalSSHRemark action +type ModifyGlobalSSHRemarkResponse struct { + response.CommonBase + + // 接口返回消息 + Message string +} + +// NewModifyGlobalSSHRemarkRequest will create request of ModifyGlobalSSHRemark action. +func (c *PathXClient) NewModifyGlobalSSHRemarkRequest() *ModifyGlobalSSHRemarkRequest { + req := &ModifyGlobalSSHRemarkRequest{} + c.client.SetupRequest(req) + return req +} + +// ModifyGlobalSSHRemark - 修改GlobalSSH备注 +func (c *PathXClient) ModifyGlobalSSHRemark(req *ModifyGlobalSSHRemarkRequest) (*ModifyGlobalSSHRemarkResponse, error) { + var err error + var res ModifyGlobalSSHRemarkResponse + + err = c.client.InvokeAction("ModifyGlobalSSHRemark", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/pathx/types_global_ssharea.go b/services/pathx/types_global_ssharea.go new file mode 100644 index 00000000..b0012eba --- /dev/null +++ b/services/pathx/types_global_ssharea.go @@ -0,0 +1,19 @@ +package pathx + +/* + GlobalSSHArea - GlobalSSH覆盖地区,包括关联的UCloud机房信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type GlobalSSHArea struct { + + // GlobalSSH覆盖的地区,如香港、东京、洛杉矶等 + Area string + + // 地区代号,以地区AirPort Code + AreaCode string + + // ucloud机房代号构成的数组,如["hk","us-ca"] + RegionSet []string +} diff --git a/services/pathx/types_global_sshinfo.go b/services/pathx/types_global_sshinfo.go new file mode 100644 index 00000000..03531069 --- /dev/null +++ b/services/pathx/types_global_sshinfo.go @@ -0,0 +1,37 @@ +package pathx + +/* + GlobalSSHInfo - GlobalSSH实例信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type GlobalSSHInfo struct { + + // 实例ID,资源唯一标识 + InstanceId string + + // 加速域名 + AcceleratingDomain string + + // 被SSH访问的IP所在地区 + Area string + + // 被SSH访问的EIP + TargetIP string + + // 备注信息 + Remark string + + // SSH登陆端口 + Port int + + // 支付周期,如Month,Year等 + ChargeType string + + // 资源创建时间戳 + CreateTime int + + // 资源过期时间戳 + ExpireTime int +} diff --git a/services/uaccount/client.go b/services/uaccount/client.go new file mode 100644 index 00000000..8624f716 --- /dev/null +++ b/services/uaccount/client.go @@ -0,0 +1,17 @@ +package uaccount + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type UAccountClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *UAccountClient { + client := ucloud.NewClient(config, credential) + return &UAccountClient{ + client: client, + } +} diff --git a/services/uaccount/create_project.go b/services/uaccount/create_project.go new file mode 100644 index 00000000..47668100 --- /dev/null +++ b/services/uaccount/create_project.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UAccount CreateProject + +package uaccount + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateProjectRequest is request schema for CreateProject action +type CreateProjectRequest struct { + request.CommonBase + + // 项目名称 + ProjectName *string `required:"true"` + + // 项目父节点Id, 不填写创建顶层项目 + ParentId *string `required:"false"` +} + +// CreateProjectResponse is response schema for CreateProject action +type CreateProjectResponse struct { + response.CommonBase + + // 所创建项目的Id + ProjectId string +} + +// NewCreateProjectRequest will create request of CreateProject action. +func (c *UAccountClient) NewCreateProjectRequest() *CreateProjectRequest { + req := &CreateProjectRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateProject - 创建项目 +func (c *UAccountClient) CreateProject(req *CreateProjectRequest) (*CreateProjectResponse, error) { + var err error + var res CreateProjectResponse + + err = c.client.InvokeAction("CreateProject", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uaccount/doc.go b/services/uaccount/doc.go new file mode 100644 index 00000000..7b104998 --- /dev/null +++ b/services/uaccount/doc.go @@ -0,0 +1,11 @@ +/* + Package uhost include resources of ucloud host product + + See also + + - API: https://docs.ucloud.cn/api/uaccount-api/index + - Product: https://www.ucloud.cn/site/product/uaccount.html + + for detail. +*/ +package uaccount diff --git a/services/uaccount/get_project_list.go b/services/uaccount/get_project_list.go new file mode 100644 index 00000000..66f8fd16 --- /dev/null +++ b/services/uaccount/get_project_list.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UAccount GetProjectList + +package uaccount + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetProjectListRequest is request schema for GetProjectList action +type GetProjectListRequest struct { + request.CommonBase + + // 是否是财务账号(Yes: 是, No: 否) + IsFinance *string `required:"false"` +} + +// GetProjectListResponse is response schema for GetProjectList action +type GetProjectListResponse struct { + response.CommonBase + + // 项目总数 + ProjectCount int + + // JSON格式的项目列表实例 + ProjectSet []ProjectListInfo +} + +// NewGetProjectListRequest will create request of GetProjectList action. +func (c *UAccountClient) NewGetProjectListRequest() *GetProjectListRequest { + req := &GetProjectListRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// GetProjectList - 获取项目列表 +func (c *UAccountClient) GetProjectList(req *GetProjectListRequest) (*GetProjectListResponse, error) { + var err error + var res GetProjectListResponse + + err = c.client.InvokeAction("GetProjectList", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uaccount/get_region.go b/services/uaccount/get_region.go new file mode 100644 index 00000000..08a5591e --- /dev/null +++ b/services/uaccount/get_region.go @@ -0,0 +1,47 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UAccount GetRegion + +package uaccount + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetRegionRequest is request schema for GetRegion action +type GetRegionRequest struct { + request.CommonBase +} + +// GetRegionResponse is response schema for GetRegion action +type GetRegionResponse struct { + response.CommonBase + + // 各数据中心信息 + Regions []RegionInfo +} + +// NewGetRegionRequest will create request of GetRegion action. +func (c *UAccountClient) NewGetRegionRequest() *GetRegionRequest { + req := &GetRegionRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// GetRegion - 获取用户在各数据中心的权限等信息 +func (c *UAccountClient) GetRegion(req *GetRegionRequest) (*GetRegionResponse, error) { + var err error + var res GetRegionResponse + + err = c.client.InvokeAction("GetRegion", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uaccount/get_user_info.go b/services/uaccount/get_user_info.go new file mode 100644 index 00000000..b548e262 --- /dev/null +++ b/services/uaccount/get_user_info.go @@ -0,0 +1,47 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UAccount GetUserInfo + +package uaccount + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetUserInfoRequest is request schema for GetUserInfo action +type GetUserInfoRequest struct { + request.CommonBase +} + +// GetUserInfoResponse is response schema for GetUserInfo action +type GetUserInfoResponse struct { + response.CommonBase + + // 用户信息返回数组 + DataSet []UserInfo +} + +// NewGetUserInfoRequest will create request of GetUserInfo action. +func (c *UAccountClient) NewGetUserInfoRequest() *GetUserInfoRequest { + req := &GetUserInfoRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// GetUserInfo - 获取用户信息 +func (c *UAccountClient) GetUserInfo(req *GetUserInfoRequest) (*GetUserInfoResponse, error) { + var err error + var res GetUserInfoResponse + + err = c.client.InvokeAction("GetUserInfo", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uaccount/modify_project.go b/services/uaccount/modify_project.go new file mode 100644 index 00000000..26968851 --- /dev/null +++ b/services/uaccount/modify_project.go @@ -0,0 +1,47 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UAccount ModifyProject + +package uaccount + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ModifyProjectRequest is request schema for ModifyProject action +type ModifyProjectRequest struct { + request.CommonBase + + // 新的项目名称 + ProjectName *string `required:"true"` +} + +// ModifyProjectResponse is response schema for ModifyProject action +type ModifyProjectResponse struct { + response.CommonBase +} + +// NewModifyProjectRequest will create request of ModifyProject action. +func (c *UAccountClient) NewModifyProjectRequest() *ModifyProjectRequest { + req := &ModifyProjectRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ModifyProject - 修改项目 +func (c *UAccountClient) ModifyProject(req *ModifyProjectRequest) (*ModifyProjectResponse, error) { + var err error + var res ModifyProjectResponse + + err = c.client.InvokeAction("ModifyProject", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uaccount/terminate_project.go b/services/uaccount/terminate_project.go new file mode 100644 index 00000000..9f635f0e --- /dev/null +++ b/services/uaccount/terminate_project.go @@ -0,0 +1,44 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UAccount TerminateProject + +package uaccount + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// TerminateProjectRequest is request schema for TerminateProject action +type TerminateProjectRequest struct { + request.CommonBase +} + +// TerminateProjectResponse is response schema for TerminateProject action +type TerminateProjectResponse struct { + response.CommonBase +} + +// NewTerminateProjectRequest will create request of TerminateProject action. +func (c *UAccountClient) NewTerminateProjectRequest() *TerminateProjectRequest { + req := &TerminateProjectRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// TerminateProject - 删除项目 +func (c *UAccountClient) TerminateProject(req *TerminateProjectRequest) (*TerminateProjectResponse, error) { + var err error + var res TerminateProjectResponse + + err = c.client.InvokeAction("TerminateProject", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uaccount/types_project_list_info.go b/services/uaccount/types_project_list_info.go new file mode 100644 index 00000000..8df6549c --- /dev/null +++ b/services/uaccount/types_project_list_info.go @@ -0,0 +1,34 @@ +package uaccount + +/* + ProjectListInfo - 项目信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ProjectListInfo struct { + + // 项目ID + ProjectId string + + // 项目名称 + ProjectName string + + // 父项目ID + ParentId string + + // 父项目名称 + ParentName string + + // 创建时间(Unix时间戳) + CreateTime int + + // 是否为默认项目 + IsDefault bool + + // 项目下资源数量 + ResourceCount int + + // 项目下成员数量 + MemberCount int +} diff --git a/services/uaccount/types_region_info.go b/services/uaccount/types_region_info.go new file mode 100644 index 00000000..99eb8469 --- /dev/null +++ b/services/uaccount/types_region_info.go @@ -0,0 +1,28 @@ +package uaccount + +/* + RegionInfo - 数据中心信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type RegionInfo struct { + + // 数据中心ID + RegionId int + + // 数据中心名称 + RegionName string + + // 是否用户当前默认数据中心 + IsDefault bool + + // 用户在此数据中心的权限位 + BitMaps string + + // 地域名字,如cn-bj + Region string + + // 可用区名字,如cn-bj-01 + Zone string +} diff --git a/services/uaccount/types_user_info.go b/services/uaccount/types_user_info.go new file mode 100644 index 00000000..7d99026c --- /dev/null +++ b/services/uaccount/types_user_info.go @@ -0,0 +1,58 @@ +package uaccount + +/* + UserInfo - 用户信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UserInfo struct { + + // 用户Id + UserId int + + // 用户邮箱 + UserEmail string + + // 用户手机 + UserPhone string + + // 国际号码前缀 + PhonePrefix string + + // 会员类型 + UserType int + + // 称呼 + UserName string + + // 公司名称 + CompanyName string + + // 所属行业 + IndustryType int + + // 省份 + Province string + + // 城市 + City string + + // 公司地址 + UserAddress string + + // 是否超级管理员 0:否 1:是 + Admin int + + // 是否子帐户(大于100为子帐户) + UserVersion int + + // 是否有财务权限 0:否 1:是 + Finance int + + // 管理员 + Administrator string + + // 实名认证状态 + AuthState string +} diff --git a/services/udisk/attach_udisk.go b/services/udisk/attach_udisk.go new file mode 100644 index 00000000..65b6460a --- /dev/null +++ b/services/udisk/attach_udisk.go @@ -0,0 +1,59 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk AttachUDisk + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// AttachUDiskRequest is request schema for AttachUDisk action +type AttachUDiskRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // UHost实例ID + UHostId *string `required:"true"` + + // 需要挂载的UDisk实例ID + UDiskId *string `required:"true"` +} + +// AttachUDiskResponse is response schema for AttachUDisk action +type AttachUDiskResponse struct { + response.CommonBase + + // 挂载的UHost实例ID + UHostId string + + // 挂载的UDisk实例ID + UDiskId string +} + +// NewAttachUDiskRequest will create request of AttachUDisk action. +func (c *UDiskClient) NewAttachUDiskRequest() *AttachUDiskRequest { + req := &AttachUDiskRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// AttachUDisk - 将一个可用的UDisk挂载到某台主机上,当UDisk挂载成功后,还需要在主机内部进行文件系统操作 +func (c *UDiskClient) AttachUDisk(req *AttachUDiskRequest) (*AttachUDiskResponse, error) { + var err error + var res AttachUDiskResponse + + err = c.client.InvokeAction("AttachUDisk", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/client.go b/services/udisk/client.go new file mode 100644 index 00000000..a58904bf --- /dev/null +++ b/services/udisk/client.go @@ -0,0 +1,19 @@ +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +// UDiskClient is the client of ucloud disk +type UDiskClient struct { + client *ucloud.Client +} + +// NewClient will create an instance of UDiskClient +func NewClient(config *ucloud.Config, credential *auth.Credential) *UDiskClient { + client := ucloud.NewClient(config, credential) + return &UDiskClient{ + client: client, + } +} diff --git a/services/udisk/clone_udisk.go b/services/udisk/clone_udisk.go new file mode 100644 index 00000000..b2a0ca80 --- /dev/null +++ b/services/udisk/clone_udisk.go @@ -0,0 +1,71 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk CloneUDisk + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CloneUDiskRequest is request schema for CloneUDisk action +type CloneUDiskRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 实例名称 + Name *string `required:"true"` + + // 克隆父Disk的Id + SourceId *string `required:"true"` + + // 方舟是否开启,"Yes":开启,"No":关闭;默认为"No" + UDataArkMode *string `required:"false"` + + // 购买时长 默认: 1 + Quantity *int `required:"false"` + + // Disk注释 + Comment *string `required:"false"` + + // Year , Month, Dynamic 默认: Dynamic + ChargeType *string `required:"false"` + + // 使用的代金券id + CouponId *string `required:"false"` +} + +// CloneUDiskResponse is response schema for CloneUDisk action +type CloneUDiskResponse struct { + response.CommonBase + + // 创建UDisk Id + UDiskId []string +} + +// NewCloneUDiskRequest will create request of CloneUDisk action. +func (c *UDiskClient) NewCloneUDiskRequest() *CloneUDiskRequest { + req := &CloneUDiskRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CloneUDisk - 从UDisk创建UDisk克隆 +func (c *UDiskClient) CloneUDisk(req *CloneUDiskRequest) (*CloneUDiskResponse, error) { + var err error + var res CloneUDiskResponse + + err = c.client.InvokeAction("CloneUDisk", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/clone_udisk_snapshot.go b/services/udisk/clone_udisk_snapshot.go new file mode 100644 index 00000000..013df95b --- /dev/null +++ b/services/udisk/clone_udisk_snapshot.go @@ -0,0 +1,69 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk CloneUDiskSnapshot + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CloneUDiskSnapshotRequest is request schema for CloneUDiskSnapshot action +type CloneUDiskSnapshotRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 实例名称 + Name *string `required:"true"` + + // 克隆父Snapshot的Id + SourceId *string `required:"true"` + + // 购买UDisk大小,单位:GB,范围[1~2000], 权限位控制可达8T,若需要请申请开通相关权限。 + Size *int `required:"true"` + + // Disk注释 + Comment *string `required:"false"` + + // Year , Month, Dynamic 默认: Dynamic + ChargeType *string `required:"false"` + + // 购买时长 默认: 1 + Quantity *int `required:"false"` + + // 是否开启数据方舟 默认:No + UDataArkMode *string `required:"false"` + + // 使用的代金券id + CouponId *string `required:"false"` +} + +// CloneUDiskSnapshotResponse is response schema for CloneUDiskSnapshot action +type CloneUDiskSnapshotResponse struct { + response.CommonBase + + // 创建UDisk Id + UDiskId []string +} + +// NewCloneUDiskSnapshotRequest will create request of CloneUDiskSnapshot action. +func (c *UDiskClient) NewCloneUDiskSnapshotRequest() *CloneUDiskSnapshotRequest { + req := &CloneUDiskSnapshotRequest{} + c.client.SetupRequest(req) + return req +} + +// CloneUDiskSnapshot - 从快照创建UDisk克隆 +func (c *UDiskClient) CloneUDiskSnapshot(req *CloneUDiskSnapshotRequest) (*CloneUDiskSnapshotResponse, error) { + var err error + var res CloneUDiskSnapshotResponse + + err = c.client.InvokeAction("CloneUDiskSnapshot", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/create_udisk.go b/services/udisk/create_udisk.go new file mode 100644 index 00000000..87c7b1a9 --- /dev/null +++ b/services/udisk/create_udisk.go @@ -0,0 +1,74 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk CreateUDisk + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateUDiskRequest is request schema for CreateUDisk action +type CreateUDiskRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 购买UDisk大小,单位:GB,普通盘: 范围[1~2000], 权限位控制可达8T,若需要请申请开通相关权限;SSD盘: 范围[1~4000]。 + Size *int `required:"true"` + + // 实例名称 + Name *string `required:"true"` + + // Year , Month, Dynamic, Trial 默认: Dynamic + ChargeType *string `required:"false"` + + // 购买时长 默认: 1 + Quantity *int `required:"false"` + + // 是否开启数据方舟 + UDataArkMode *string `required:"false"` + + // 业务组 默认:Default + Tag *string `required:"false"` + + // UDisk 类型: DataDisk(普通数据盘),SSDDataDisk(SSD数据盘),默认值(DataDisk) + DiskType *string `required:"false"` + + // 使用的代金券id + CouponId *string `required:"false"` +} + +// CreateUDiskResponse is response schema for CreateUDisk action +type CreateUDiskResponse struct { + response.CommonBase + + // UDisk实例Id + UDiskId []string +} + +// NewCreateUDiskRequest will create request of CreateUDisk action. +func (c *UDiskClient) NewCreateUDiskRequest() *CreateUDiskRequest { + req := &CreateUDiskRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateUDisk - 创建UDisk磁盘 +func (c *UDiskClient) CreateUDisk(req *CreateUDiskRequest) (*CreateUDiskResponse, error) { + var err error + var res CreateUDiskResponse + + err = c.client.InvokeAction("CreateUDisk", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/create_udisk_snapshot.go b/services/udisk/create_udisk_snapshot.go new file mode 100644 index 00000000..d6326886 --- /dev/null +++ b/services/udisk/create_udisk_snapshot.go @@ -0,0 +1,60 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk CreateUDiskSnapshot + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateUDiskSnapshotRequest is request schema for CreateUDiskSnapshot action +type CreateUDiskSnapshotRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 快照的UDisk的Id + UDiskId *string `required:"true"` + + // 快照名称 + Name *string `required:"true"` + + // Year , Month, Dynamic 默认: Dynamic + ChargeType *string `required:"false"` + + // 购买时长 默认: 1 + Quantity *int `required:"false"` + + // 快照描述 + Comment *string `required:"false"` +} + +// CreateUDiskSnapshotResponse is response schema for CreateUDiskSnapshot action +type CreateUDiskSnapshotResponse struct { + response.CommonBase + + // 快照Id + SnapshotId []string +} + +// NewCreateUDiskSnapshotRequest will create request of CreateUDiskSnapshot action. +func (c *UDiskClient) NewCreateUDiskSnapshotRequest() *CreateUDiskSnapshotRequest { + req := &CreateUDiskSnapshotRequest{} + c.client.SetupRequest(req) + return req +} + +// CreateUDiskSnapshot - 创建snapshot快照 +func (c *UDiskClient) CreateUDiskSnapshot(req *CreateUDiskSnapshotRequest) (*CreateUDiskSnapshotResponse, error) { + var err error + var res CreateUDiskSnapshotResponse + + err = c.client.InvokeAction("CreateUDiskSnapshot", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/delete_udisk.go b/services/udisk/delete_udisk.go new file mode 100644 index 00000000..6e9775f9 --- /dev/null +++ b/services/udisk/delete_udisk.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk DeleteUDisk + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeleteUDiskRequest is request schema for DeleteUDisk action +type DeleteUDiskRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 要删除的UDisk的Id + UDiskId *string `required:"true"` +} + +// DeleteUDiskResponse is response schema for DeleteUDisk action +type DeleteUDiskResponse struct { + response.CommonBase +} + +// NewDeleteUDiskRequest will create request of DeleteUDisk action. +func (c *UDiskClient) NewDeleteUDiskRequest() *DeleteUDiskRequest { + req := &DeleteUDiskRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DeleteUDisk - 删除UDisk +func (c *UDiskClient) DeleteUDisk(req *DeleteUDiskRequest) (*DeleteUDiskResponse, error) { + var err error + var res DeleteUDiskResponse + + err = c.client.InvokeAction("DeleteUDisk", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/describe_udisk.go b/services/udisk/describe_udisk.go new file mode 100644 index 00000000..7a8f878d --- /dev/null +++ b/services/udisk/describe_udisk.go @@ -0,0 +1,65 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk DescribeUDisk + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeUDiskRequest is request schema for DescribeUDisk action +type DescribeUDiskRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UDisk Id(留空返回全部) + UDiskId *string `required:"false"` + + // 数据偏移量, 默认为0 + Offset *int `required:"false"` + + // 返回数据长度, 默认为20 + Limit *int `required:"false"` + + // 普通数据盘:DataDisk|普通系统盘:SystemDisk|SSD数据盘:SSDDataDisk; 为空拉取所有 + DiskType *string `required:"false"` +} + +// DescribeUDiskResponse is response schema for DescribeUDisk action +type DescribeUDiskResponse struct { + response.CommonBase + + // JSON 格式的UDisk数据列表, 每项参数可见下面 UDiskDataSet + DataSet []UDiskDataSet + + // 根据过滤条件得到的总数 + TotalCount int +} + +// NewDescribeUDiskRequest will create request of DescribeUDisk action. +func (c *UDiskClient) NewDescribeUDiskRequest() *DescribeUDiskRequest { + req := &DescribeUDiskRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeUDisk - 获取UDisk实例 +func (c *UDiskClient) DescribeUDisk(req *DescribeUDiskRequest) (*DescribeUDiskResponse, error) { + var err error + var res DescribeUDiskResponse + + err = c.client.InvokeAction("DescribeUDisk", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/describe_udisk_price.go b/services/udisk/describe_udisk_price.go new file mode 100644 index 00000000..5959af93 --- /dev/null +++ b/services/udisk/describe_udisk_price.go @@ -0,0 +1,65 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk DescribeUDiskPrice + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeUDiskPriceRequest is request schema for DescribeUDiskPrice action +type DescribeUDiskPriceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 购买UDisk大小,单位:GB,范围[1~1000] + Size *int `required:"true"` + + // Year, Month, Dynamic,Trial,默认: Dynamic 如果不指定,则一次性获取三种计费 + ChargeType *string `required:"false"` + + // 购买UDisk的时长,默认值为1 + Quantity *int `required:"false"` + + // 是否打开数据方舟, 打开"Yes",关闭"No", 默认关闭 + UDataArkMode *string `required:"false"` + + // UDisk 类型: DataDisk(普通数据盘),SSDDataDisk(SSD数据盘),默认值(DataDisk) + DiskType *string `required:"false"` +} + +// DescribeUDiskPriceResponse is response schema for DescribeUDiskPrice action +type DescribeUDiskPriceResponse struct { + response.CommonBase + + // 价格参数列表,具体说明见 UDiskPriceDataSet + DataSet []UDiskPriceDataSet +} + +// NewDescribeUDiskPriceRequest will create request of DescribeUDiskPrice action. +func (c *UDiskClient) NewDescribeUDiskPriceRequest() *DescribeUDiskPriceRequest { + req := &DescribeUDiskPriceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeUDiskPrice - 获取UDisk实例价格信息 +func (c *UDiskClient) DescribeUDiskPrice(req *DescribeUDiskPriceRequest) (*DescribeUDiskPriceResponse, error) { + var err error + var res DescribeUDiskPriceResponse + + err = c.client.InvokeAction("DescribeUDiskPrice", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/describe_udisk_upgrade_price.go b/services/udisk/describe_udisk_upgrade_price.go new file mode 100644 index 00000000..73e5f592 --- /dev/null +++ b/services/udisk/describe_udisk_upgrade_price.go @@ -0,0 +1,62 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk DescribeUDiskUpgradePrice + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeUDiskUpgradePriceRequest is request schema for DescribeUDiskUpgradePrice action +type DescribeUDiskUpgradePriceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 购买UDisk大小,单位:GB,范围[1~2000], 权限位控制可达8T,若需要请申请开通相关权限。 + Size *int `required:"true"` + + // 升级目标UDisk ID + SourceId *string `required:"true"` + + // 是否打开数据方舟, 打开"Yes",关闭"No", 默认关闭 + UDataArkMode *string `required:"true"` + + // 磁盘类型,SSDDataDisk:ssd数据盘,DataDisk:普通数据盘。默认为DataDisk + DiskType *string `required:"false"` +} + +// DescribeUDiskUpgradePriceResponse is response schema for DescribeUDiskUpgradePrice action +type DescribeUDiskUpgradePriceResponse struct { + response.CommonBase + + // 价格 + Price float64 +} + +// NewDescribeUDiskUpgradePriceRequest will create request of DescribeUDiskUpgradePrice action. +func (c *UDiskClient) NewDescribeUDiskUpgradePriceRequest() *DescribeUDiskUpgradePriceRequest { + req := &DescribeUDiskUpgradePriceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeUDiskUpgradePrice - 获取UDisk升级价格信息 +func (c *UDiskClient) DescribeUDiskUpgradePrice(req *DescribeUDiskUpgradePriceRequest) (*DescribeUDiskUpgradePriceResponse, error) { + var err error + var res DescribeUDiskUpgradePriceResponse + + err = c.client.InvokeAction("DescribeUDiskUpgradePrice", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/detach_udisk.go b/services/udisk/detach_udisk.go new file mode 100644 index 00000000..063f4419 --- /dev/null +++ b/services/udisk/detach_udisk.go @@ -0,0 +1,59 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk DetachUDisk + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DetachUDiskRequest is request schema for DetachUDisk action +type DetachUDiskRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // UHost实例ID + UHostId *string `required:"true"` + + // 需要卸载的UDisk实例ID + UDiskId *string `required:"true"` +} + +// DetachUDiskResponse is response schema for DetachUDisk action +type DetachUDiskResponse struct { + response.CommonBase + + // 卸载的UHost实例ID + UHostId string + + // 卸载的UDisk实例ID + UDiskId string +} + +// NewDetachUDiskRequest will create request of DetachUDisk action. +func (c *UDiskClient) NewDetachUDiskRequest() *DetachUDiskRequest { + req := &DetachUDiskRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DetachUDisk - 卸载某个已经挂载在指定UHost实例上的UDisk +func (c *UDiskClient) DetachUDisk(req *DetachUDiskRequest) (*DetachUDiskResponse, error) { + var err error + var res DetachUDiskResponse + + err = c.client.InvokeAction("DetachUDisk", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/doc.go b/services/udisk/doc.go new file mode 100644 index 00000000..2602d14c --- /dev/null +++ b/services/udisk/doc.go @@ -0,0 +1,11 @@ +/* + Package udisk include resources of ucloud disk product + + See also + + - API: https://docs.ucloud.cn/api/udisk-api/index + - Product: https://www.ucloud.cn/site/product/udisk.html + + for detail. +*/ +package udisk diff --git a/services/udisk/enums.go b/services/udisk/enums.go new file mode 100644 index 00000000..e4f6b1f0 --- /dev/null +++ b/services/udisk/enums.go @@ -0,0 +1 @@ +package udisk diff --git a/services/udisk/rename_udisk.go b/services/udisk/rename_udisk.go new file mode 100644 index 00000000..663f30a5 --- /dev/null +++ b/services/udisk/rename_udisk.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk RenameUDisk + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// RenameUDiskRequest is request schema for RenameUDisk action +type RenameUDiskRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 重命名的UDisk的Id + UDiskId *string `required:"true"` + + // 重命名UDisk的name + UDiskName *string `required:"true"` +} + +// RenameUDiskResponse is response schema for RenameUDisk action +type RenameUDiskResponse struct { + response.CommonBase +} + +// NewRenameUDiskRequest will create request of RenameUDisk action. +func (c *UDiskClient) NewRenameUDiskRequest() *RenameUDiskRequest { + req := &RenameUDiskRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// RenameUDisk - 重命名UDisk +func (c *UDiskClient) RenameUDisk(req *RenameUDiskRequest) (*RenameUDiskResponse, error) { + var err error + var res RenameUDiskResponse + + err = c.client.InvokeAction("RenameUDisk", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/resize_udisk.go b/services/udisk/resize_udisk.go new file mode 100644 index 00000000..277a7678 --- /dev/null +++ b/services/udisk/resize_udisk.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk ResizeUDisk + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ResizeUDiskRequest is request schema for ResizeUDisk action +type ResizeUDiskRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // UDisk Id + UDiskId *string `required:"true"` + + // 调整后大小, 单位:GB, 范围[1~2000],权限位控制可达8000,若需要请申请开通相关权限。 + Size *int `required:"true"` + + // 使用的代金券id + CouponId *string `required:"false"` +} + +// ResizeUDiskResponse is response schema for ResizeUDisk action +type ResizeUDiskResponse struct { + response.CommonBase +} + +// NewResizeUDiskRequest will create request of ResizeUDisk action. +func (c *UDiskClient) NewResizeUDiskRequest() *ResizeUDiskRequest { + req := &ResizeUDiskRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ResizeUDisk - 调整UDisk容量 +func (c *UDiskClient) ResizeUDisk(req *ResizeUDiskRequest) (*ResizeUDiskResponse, error) { + var err error + var res ResizeUDiskResponse + + err = c.client.InvokeAction("ResizeUDisk", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/restore_udisk.go b/services/udisk/restore_udisk.go new file mode 100644 index 00000000..d4b5d670 --- /dev/null +++ b/services/udisk/restore_udisk.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk RestoreUDisk + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// RestoreUDiskRequest is request schema for RestoreUDisk action +type RestoreUDiskRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 需要恢复的盘id + UDiskId *string `required:"true"` + + // 从指定的快照恢复 + SnapshotId *string `required:"false"` + + // 指定从方舟恢复的备份时间点 + SnapshotTime *int `required:"false"` +} + +// RestoreUDiskResponse is response schema for RestoreUDisk action +type RestoreUDiskResponse struct { + response.CommonBase +} + +// NewRestoreUDiskRequest will create request of RestoreUDisk action. +func (c *UDiskClient) NewRestoreUDiskRequest() *RestoreUDiskRequest { + req := &RestoreUDiskRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// RestoreUDisk - 从备份恢复数据至UDisk +func (c *UDiskClient) RestoreUDisk(req *RestoreUDiskRequest) (*RestoreUDiskResponse, error) { + var err error + var res RestoreUDiskResponse + + err = c.client.InvokeAction("RestoreUDisk", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/set_udisk_udata_ark_mode.go b/services/udisk/set_udisk_udata_ark_mode.go new file mode 100644 index 00000000..0b34fb3a --- /dev/null +++ b/services/udisk/set_udisk_udata_ark_mode.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UDisk SetUDiskUDataArkMode + +package udisk + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// SetUDiskUDataArkModeRequest is request schema for SetUDiskUDataArkMode action +type SetUDiskUDataArkModeRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 需要设置数据方舟的UDisk的Id + UDiskId *string `required:"true"` + + // 是否开启数据方舟,开启:"Yes", 不支持:"No" + UDataArkMode *string `required:"true"` +} + +// SetUDiskUDataArkModeResponse is response schema for SetUDiskUDataArkMode action +type SetUDiskUDataArkModeResponse struct { + response.CommonBase +} + +// NewSetUDiskUDataArkModeRequest will create request of SetUDiskUDataArkMode action. +func (c *UDiskClient) NewSetUDiskUDataArkModeRequest() *SetUDiskUDataArkModeRequest { + req := &SetUDiskUDataArkModeRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// SetUDiskUDataArkMode - 设置UDisk数据方舟的状态 +func (c *UDiskClient) SetUDiskUDataArkMode(req *SetUDiskUDataArkModeRequest) (*SetUDiskUDataArkModeResponse, error) { + var err error + var res SetUDiskUDataArkModeResponse + + err = c.client.InvokeAction("SetUDiskUDataArkMode", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/udisk/types_udisk_data_set.go b/services/udisk/types_udisk_data_set.go new file mode 100644 index 00000000..b102f20d --- /dev/null +++ b/services/udisk/types_udisk_data_set.go @@ -0,0 +1,64 @@ +package udisk + +/* + UDiskDataSet - DescribeUDisk + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UDiskDataSet struct { + + // UDisk实例Id + UDiskId string + + // 实例名称 + Name string + + // 容量单位GB + Size int + + // 状态:Available(可用),Attaching(挂载中), InUse(已挂载), Detaching(卸载中), Initializating(分配中), Failed(创建失败),Cloning(克隆中),Restoring(恢复中),RestoreFailed(恢复失败), + Status string + + // 创建时间 + CreateTime int + + // 过期时间 + ExpiredTime int + + // 挂载的UHost的Id + UHostId string + + // 挂载的UHost的Name + UHostName string + + // 挂载的UHost的IP + UHostIP string + + // 挂载的设备名称 + DeviceName string + + // Year,Month,Dynamic,Trial + ChargeType string + + // 业务组名称 + Tag string + + // 资源是否过期,过期:"Yes", 未过期:"No" + IsExpire string + + // 是否支持数据方舟,支持:"2.0", 不支持:"1.0" + Version string + + // 是否开启数据方舟,开启:"Yes", 不支持:"No" + UDataArkMode string + + // 该盘快照个数 + SnapshotCount int + + // 该盘快照上限 + SnapshotLimit int + + // 云硬盘类型: 普通数据盘:DataDisk,普通系统盘:SystemDisk,SSD数据盘:SSDDataDisk + DiskType string +} diff --git a/services/udisk/types_udisk_price_data_set.go b/services/udisk/types_udisk_price_data_set.go new file mode 100644 index 00000000..cf9273e4 --- /dev/null +++ b/services/udisk/types_udisk_price_data_set.go @@ -0,0 +1,19 @@ +package udisk + +/* + UDiskPriceDataSet - DescribeUDiskPrice + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UDiskPriceDataSet struct { + + // Year, Month, Dynamic,Trial + ChargeType string + + // 价格 (单位: 分) + Price float64 + + // "UDataArk","UDisk" + ChargeName string +} diff --git a/services/uhost/client.go b/services/uhost/client.go new file mode 100644 index 00000000..0943fb18 --- /dev/null +++ b/services/uhost/client.go @@ -0,0 +1,17 @@ +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type UHostClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *UHostClient { + client := ucloud.NewClient(config, credential) + return &UHostClient{ + client: client, + } +} diff --git a/services/uhost/copy_custom_image.go b/services/uhost/copy_custom_image.go new file mode 100644 index 00000000..6461dcd1 --- /dev/null +++ b/services/uhost/copy_custom_image.go @@ -0,0 +1,65 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost CopyCustomImage + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CopyCustomImageRequest is request schema for CopyCustomImage action +type CopyCustomImageRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // 源镜像Id, 参见 DescribeImage + SourceImageId *string `required:"true"` + + // 目标项目Id, 参见 GetProjectList + TargetProjectId *string `required:"true"` + + // 目标地域,不跨地域不用填 + TargetRegion *string `required:"false"` + + // 目标镜像名称 + TargetImageName *string `required:"false"` + + // 目标镜像描述 + TargetImageDescription *string `required:"false"` +} + +// CopyCustomImageResponse is response schema for CopyCustomImage action +type CopyCustomImageResponse struct { + response.CommonBase + + // 目标镜像Id + TargetImageId string +} + +// NewCopyCustomImageRequest will create request of CopyCustomImage action. +func (c *UHostClient) NewCopyCustomImageRequest() *CopyCustomImageRequest { + req := &CopyCustomImageRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CopyCustomImage - 复制自制镜像 +func (c *UHostClient) CopyCustomImage(req *CopyCustomImageRequest) (*CopyCustomImageResponse, error) { + var err error + var res CopyCustomImageResponse + + err = c.client.InvokeAction("CopyCustomImage", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/create_custom_image.go b/services/uhost/create_custom_image.go new file mode 100644 index 00000000..c9744eee --- /dev/null +++ b/services/uhost/create_custom_image.go @@ -0,0 +1,59 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost CreateCustomImage + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateCustomImageRequest is request schema for CreateCustomImage action +type CreateCustomImageRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` + + // 镜像名称 + ImageName *string `required:"true"` + + // 镜像描述 + ImageDescription *string `required:"false"` +} + +// CreateCustomImageResponse is response schema for CreateCustomImage action +type CreateCustomImageResponse struct { + response.CommonBase + + // 镜像Id + ImageId string +} + +// NewCreateCustomImageRequest will create request of CreateCustomImage action. +func (c *UHostClient) NewCreateCustomImageRequest() *CreateCustomImageRequest { + req := &CreateCustomImageRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateCustomImage - 从指定UHost实例,生成自定义镜像。 +func (c *UHostClient) CreateCustomImage(req *CreateCustomImageRequest) (*CreateCustomImageResponse, error) { + var err error + var res CreateCustomImageResponse + + err = c.client.InvokeAction("CreateCustomImage", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/create_uhost_instance.go b/services/uhost/create_uhost_instance.go new file mode 100644 index 00000000..38564271 --- /dev/null +++ b/services/uhost/create_uhost_instance.go @@ -0,0 +1,147 @@ +package uhost + +import ( + "encoding/base64" + + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateUHostInstanceRequest is request schema for CreateUHostInstance action +type CreateUHostInstanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // 镜像ID。 请通过 [DescribeImage](describe_image.html)获取 + ImageId *string `required:"true"` + + // UHost密码,LoginMode为Password时此项必须(密码需使用base64进行编码) + Password *string `required:"true"` + + // 磁盘列表 + Disks []UHostDisk `required:"true"` + + // UHost实例名称。默认:UHost + Name *string `required:"false"` + + // 业务组。默认:Default(Default即为未分组) + Tag *string `required:"false"` + + // 计费模式。枚举值为: Year,按年付费; Month,按月付费; Dynamic,按小时付费(需开启权限)。默认为月付 + ChargeType *string `required:"false"` + + // 购买时长。默认: 1。按小时购买(Dynamic)时无需此参数。 月付时,此参数传0,代表了购买至月末。 + Quantity *int `required:"false"` + + // 云主机机型。枚举值:N1:系列1标准型;N2:系列2标准型;I1: 系列1高IO型;I2,系列2高IO型; D1: 系列1大数据机型;G1: 系列1GPU型,型号为K80;G2:系列2GPU型,型号为P40;G3:系列2GPU型,型号为V100;北京A、北京C、上海二A、香港A可用区默认N1,其他机房默认N2。不同机房的主机类型支持情况不同。详情请参考控制台。 + UHostType *string `required:"false"` + + // 虚拟CPU核数。 单位:个。可选参数:{1,2,4,8,12,16,24,32}。默认值: 4 + CPU *int `required:"false"` + + // 内存大小。单位:MB。范围 :[1024, 131072], 取值为2的幂次方。默认值:8192。 + Memory *int `required:"false"` + + // GPU卡核心数。仅GPU机型支持此字段;系列1可选1,2;系列2可选1,2,3,4。GPU可选数量与CPU有关联,详情请参考控制台。 + GPU *int `required:"false"` + + // 主机登陆模式。密码(默认选项): Password,key: KeyPair(此项暂不支持) + LoginMode *string `required:"false"` + + // 【暂不支持】Keypair公钥,LoginMode为KeyPair时此项必须 + KeyPair *string `required:"false"` + + // 【待废弃,不建议调用】磁盘类型,同时设定系统盘和数据盘的磁盘类型。枚举值为:LocalDisk,本地磁盘; UDisk,云硬盘;默认为LocalDisk。仅部分可用区支持云硬盘方式的主机存储方式,具体请查询控制台。 + StorageType *string `required:"false"` + + // 【待废弃,不建议调用】系统盘大小。 单位:GB, 范围[20,100], 步长:10 + BootDiskSpace *int `required:"false"` + + // 【待废弃,不建议调用】数据盘大小。 单位:GB, 范围[0,8000], 步长:10, 默认值:20,云盘支持0-8000;本地普通盘支持0-2000;本地SSD盘(包括所有GPU机型)支持100-1000 + DiskSpace *int `required:"false"` + + // 网络增强。目前仅Normal(不开启) 和Super(开启)可用。默认Normal。 不同机房的网络增强支持情况不同。详情请参考控制台。 + NetCapability *string `required:"false"` + + // 是否开启方舟特性。Yes为开启方舟,No为关闭方舟。目前仅选择普通本地盘+普通本地盘 或 SSD云盘+普通云盘的组合支持开启方舟。 + TimemachineFeature *string `required:"false"` + + // 是否开启热升级特性。True为开启,False为未开启,默认False。仅系列1云主机需要使用此字段,系列2云主机根据镜像是否支持云主机。 + HotplugFeature *bool `required:"false"` + + // 加密盘的密码。若输入此字段,自动选择加密盘。加密盘需要权限位。 + DiskPassword *string `required:"false"` + + // 网络ID(VPC2.0情况下无需填写)。VPC1.0情况下,若不填写,代表选择基础网络; 若填写,代表选择子网。参见DescribeSubnet。 + NetworkId *string `required:"false"` + + // VPC ID。VPC2.0下需要填写此字段。 + VPCId *string `required:"false"` + + // 子网ID。VPC2.0下需要填写此字段。 + SubnetId *string `required:"false"` + + // 【数组】创建云主机时指定内网IP。当前只支持一个内网IP。调用方式举例:PrivateIp.0=x.x.x.x。 + PrivateIp []string `required:"false"` + + // 创建云主机时指定Mac。调用方式举例:PrivateMac="xx:xx:xx:xx:xx:xx"。 + PrivateMac *string `required:"false"` + + // 防火墙Id,默认:Web推荐防火墙。如何查询SecurityGroupId请参见 [DescribeSecurityGroup](../unet-api/describe_security_group.html) + SecurityGroupId *string `required:"false"` + + // 【暂不支持】cloudinit方式下,用户初始化脚本 + UserDataScript *string `required:"false"` + + // 【已废弃】宿主机类型,N2,N1 + HostType *string `required:"false"` + + // 【暂不支持】是否安装UGA。'yes': 安装;其他或者不填:不安装。 + InstallAgent *string `required:"false"` + + // 【内部参数】资源类型 + ResourceType *int `required:"false"` + + // 代金券ID。请通过DescribeCoupon接口查询,或登录用户中心查看 + CouponId *string `required:"false"` +} + +// CreateUHostInstanceResponse is response schema for CreateUHostInstance action +type CreateUHostInstanceResponse struct { + response.CommonBase + + // UHost实例Id集合 + UHostIds []string + + // IP信息 + IPs []string +} + +// NewCreateUHostInstanceRequest will create request of CreateUHostInstance action. +func (c *UHostClient) NewCreateUHostInstanceRequest() *CreateUHostInstanceRequest { + req := &CreateUHostInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateUHostInstance - 指定数据中心,根据资源使用量创建指定数量的UHost实例。 +func (c *UHostClient) CreateUHostInstance(req *CreateUHostInstanceRequest) (*CreateUHostInstanceResponse, error) { + var err error + var res CreateUHostInstanceResponse + req.Password = ucloud.String(base64.StdEncoding.EncodeToString([]byte(ucloud.StringValue(req.Password)))) + + err = c.client.InvokeAction("CreateUHostInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/describe_image.go b/services/uhost/describe_image.go new file mode 100644 index 00000000..ddcd8855 --- /dev/null +++ b/services/uhost/describe_image.go @@ -0,0 +1,71 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost DescribeImage + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeImageRequest is request schema for DescribeImage action +type DescribeImageRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // 镜像类型。标准镜像:Base,镜像市场:Business, 自定义镜像:Custom,默认返回所有类型 + ImageType *string `required:"false"` + + // 操作系统类型:Linux, Windows 默认返回所有类型 + OsType *string `required:"false"` + + // 镜像Id + ImageId *string `required:"false"` + + // 列表起始位置偏移量,默认为0 + Offset *int `required:"false"` + + // 返回数据长度,默认为20 + Limit *int `required:"false"` + + // 是否返回价格:1返回,0不返回;默认不返回 + PriceSet *int `required:"false"` +} + +// DescribeImageResponse is response schema for DescribeImage action +type DescribeImageResponse struct { + response.CommonBase + + // 满足条件的镜像总数 + TotalCount int + + // 镜像列表详见 UHostImageSet + ImageSet []UHostImageSet +} + +// NewDescribeImageRequest will create request of DescribeImage action. +func (c *UHostClient) NewDescribeImageRequest() *DescribeImageRequest { + req := &DescribeImageRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeImage - 获取指定数据中心镜像列表,用户可通过指定操作系统类型,镜像Id进行过滤。 +func (c *UHostClient) DescribeImage(req *DescribeImageRequest) (*DescribeImageResponse, error) { + var err error + var res DescribeImageResponse + + err = c.client.InvokeAction("DescribeImage", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/describe_uhost_instance.go b/services/uhost/describe_uhost_instance.go new file mode 100644 index 00000000..e4d650d7 --- /dev/null +++ b/services/uhost/describe_uhost_instance.go @@ -0,0 +1,68 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost DescribeUHostInstance + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeUHostInstanceRequest is request schema for DescribeUHostInstance action +type DescribeUHostInstanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // 【数组】UHost主机的资源ID,例如UHostIds.0代表希望获取信息 的主机1,UHostIds.1代表主机2。 如果不传入,则返回当前Region 所有符合条件的UHost实例。 + UHostIds []string `required:"false"` + + // 要查询的业务组名称 + Tag *string `required:"false"` + + // 1:普通云主机;2:抢占型云主机;如不传此参数,默认全部获取 + LifeCycle *int `required:"false"` + + // 列表起始位置偏移量,默认为0 + Offset *int `required:"false"` + + // 返回数据长度,默认为20,最大100 + Limit *int `required:"false"` +} + +// DescribeUHostInstanceResponse is response schema for DescribeUHostInstance action +type DescribeUHostInstanceResponse struct { + response.CommonBase + + // UHostInstance总数 + TotalCount int + + // 云主机实例列表,每项参数可见下面 UHostInstanceSet + UHostSet []UHostInstanceSet +} + +// NewDescribeUHostInstanceRequest will create request of DescribeUHostInstance action. +func (c *UHostClient) NewDescribeUHostInstanceRequest() *DescribeUHostInstanceRequest { + req := &DescribeUHostInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeUHostInstance - 获取主机或主机列表信息,并可根据数据中心,主机ID等参数进行过滤。 +func (c *UHostClient) DescribeUHostInstance(req *DescribeUHostInstanceRequest) (*DescribeUHostInstanceResponse, error) { + var err error + var res DescribeUHostInstanceResponse + + err = c.client.InvokeAction("DescribeUHostInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/describe_uhost_tags.go b/services/uhost/describe_uhost_tags.go new file mode 100644 index 00000000..e276e9c7 --- /dev/null +++ b/services/uhost/describe_uhost_tags.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost DescribeUHostTags + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeUHostTagsRequest is request schema for DescribeUHostTags action +type DescribeUHostTagsRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` +} + +// DescribeUHostTagsResponse is response schema for DescribeUHostTags action +type DescribeUHostTagsResponse struct { + response.CommonBase + + // 已有主机的业务组总个数 + TotalCount int + + // 业务组集合见 UHostTagSet + TagSet []UHostTagSet +} + +// NewDescribeUHostTagsRequest will create request of DescribeUHostTags action. +func (c *UHostClient) NewDescribeUHostTagsRequest() *DescribeUHostTagsRequest { + req := &DescribeUHostTagsRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeUHostTags - 获取指定数据中心的业务组列表。 +func (c *UHostClient) DescribeUHostTags(req *DescribeUHostTagsRequest) (*DescribeUHostTagsResponse, error) { + var err error + var res DescribeUHostTagsResponse + + err = c.client.InvokeAction("DescribeUHostTags", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/doc.go b/services/uhost/doc.go new file mode 100644 index 00000000..8bf244c6 --- /dev/null +++ b/services/uhost/doc.go @@ -0,0 +1,11 @@ +/* + Package uhost include resources of ucloud host product + + See also + + - API: https://docs.ucloud.cn/api/uhost-api/index + - Product: https://www.ucloud.cn/site/product/uhost.html + + for detail. +*/ +package uhost diff --git a/services/uhost/enums.go b/services/uhost/enums.go new file mode 100644 index 00000000..7b7614f3 --- /dev/null +++ b/services/uhost/enums.go @@ -0,0 +1,20 @@ +package uhost + +// State is the state of UHost instance +type State string + +// Enum values for State +const ( + StateInitializing State = "Initializing" + StateStarting State = "Starting" + StateRunning State = "Running" + StateStopping State = "Stopping" + StateStopped State = "Stopped" + StateInstallFail State = "InstallFail" + StateRebooting State = "Rebooting" +) + +// MarshalValue will marshal state value to string +func (enum State) MarshalValue() (string, error) { + return string(enum), nil +} diff --git a/services/uhost/get_uhost_instance_price.go b/services/uhost/get_uhost_instance_price.go new file mode 100644 index 00000000..ee63a960 --- /dev/null +++ b/services/uhost/get_uhost_instance_price.go @@ -0,0 +1,89 @@ +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetUHostInstancePriceRequest is request schema for GetUHostInstancePrice action +type GetUHostInstancePriceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // 镜像Id,可通过 [DescribeImage](describe_image.html) 获取镜像ID + ImageId *string `required:"true"` + + // 虚拟CPU核心数,单位: 个,范围: [1,16],最小值为1,其他值是2的整数倍 + CPU *int `required:"true"` + + // 内存容量大小,单位: MB,范围: [2048,65536],步长: 2048 不同机房的网络增强支持情况不同。详情请参考控制台。 + Memory *int `required:"true"` + + // 购买台数,范围[1,5] + Count *int `required:"true"` + + // 磁盘列表 + Disks []UHostDisk + + // GPU核心数,单位:个,范围[0,4] + GPU *int `required:"false"` + + // 计费类型。Year,Month,Dynamic,默认返回全部计费方式对应的价格 + ChargeType *string `required:"false"` + + // 磁盘类型,同时设定系统盘和数据盘, 枚举值为:LocalDisk,本地磁盘; UDisk,云硬盘; 默认为LocalDisk 仅部分可用区支持云硬盘方式的主机存储方式,具体请查询控制台。 + StorageType *string `required:"false"` + + // 数据盘大小,单位: GB,范围[0,1000],步长: 10,默认值: 0 + DiskSpace *int `required:"false"` + + // 网络增强 默认是Normal, 目前仅支持Normal(不开启) 和 Super(开启网络增强)。 不同机房的网络增强支持情况不同。详情请参考控制台。 + NetCapability *string `required:"false"` + + // 方舟机型。No,Yes。默认是No。 + TimemachineFeature *string `required:"false"` + + // 主机类型 Normal: 标准机型 SSD:SSD机型 BigData:大数据 GPU:GPU型G1(原GPU型) GPU_G2:GPU型G2 GPU_G3:GPU型G3 不同机房的主机类型支持情况不同。详情请参考控制台。 + UHostType *string `required:"false"` + + // 1:普通云主机;2:抢占性云主机;默认普通 + LifeCycle *int `required:"false"` + + // 购买时长。默认: 1。按小时购买(Dynamic)时无需此参数。 月付时,此参数传0,代表了购买至月末。 + Quantity *int `required:"false"` +} + +// GetUHostInstancePriceResponse is response schema for GetUHostInstancePrice action +type GetUHostInstancePriceResponse struct { + response.CommonBase + + // 价格列表 UHostPriceSet + PriceSet []UHostPriceSet +} + +// NewGetUHostInstancePriceRequest will create request of GetUHostInstancePrice action. +func (c *UHostClient) NewGetUHostInstancePriceRequest() *GetUHostInstancePriceRequest { + req := &GetUHostInstancePriceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// GetUHostInstancePrice - 根据UHost实例配置,获取UHost实例的价格。 +func (c *UHostClient) GetUHostInstancePrice(req *GetUHostInstancePriceRequest) (*GetUHostInstancePriceResponse, error) { + var err error + var res GetUHostInstancePriceResponse + + err = c.client.InvokeAction("GetUHostInstancePrice", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/get_uhost_instance_vnc_info.go b/services/uhost/get_uhost_instance_vnc_info.go new file mode 100644 index 00000000..8a5f3ff1 --- /dev/null +++ b/services/uhost/get_uhost_instance_vnc_info.go @@ -0,0 +1,62 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost GetUHostInstanceVncInfo + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetUHostInstanceVncInfoRequest is request schema for GetUHostInstanceVncInfo action +type GetUHostInstanceVncInfoRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](./describe_uhost_instance.html) + UHostId *string `required:"true"` +} + +// GetUHostInstanceVncInfoResponse is response schema for GetUHostInstanceVncInfo action +type GetUHostInstanceVncInfoResponse struct { + response.CommonBase + + // UHost实例ID + UhostId string + + // Vnc登录IP + VncIP string + + // Vnc登录端口 + VncPort int + + // Vnc 登录密码 + VncPassword string +} + +// NewGetUHostInstanceVncInfoRequest will create request of GetUHostInstanceVncInfo action. +func (c *UHostClient) NewGetUHostInstanceVncInfoRequest() *GetUHostInstanceVncInfoRequest { + req := &GetUHostInstanceVncInfoRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// GetUHostInstanceVncInfo - 获取指定UHost实例的管理VNC配置详细信息。 +func (c *UHostClient) GetUHostInstanceVncInfo(req *GetUHostInstanceVncInfoRequest) (*GetUHostInstanceVncInfoResponse, error) { + var err error + var res GetUHostInstanceVncInfoResponse + + err = c.client.InvokeAction("GetUHostInstanceVncInfo", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/get_uhost_upgrade_price.go b/services/uhost/get_uhost_upgrade_price.go new file mode 100644 index 00000000..5ac3d148 --- /dev/null +++ b/services/uhost/get_uhost_upgrade_price.go @@ -0,0 +1,74 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost GetUHostUpgradePrice + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetUHostUpgradePriceRequest is request schema for GetUHostUpgradePrice action +type GetUHostUpgradePriceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` + + // 虚拟CPU核心数,单位: 个,范围: [1,16],最小值为1,其他值是2的整数倍 默认值是该主机当前CPU数。 + CPU *int `required:"false"` + + // 内存容量大小,单位: MB,范围: [2048,65536],步长: 2048 北京BGP C机房最小支持1024(限Linux系统)。 默认值是该主机当前内存大小。 + Memory *int `required:"false"` + + // 数据盘大小,单位: GB,范围[0,1000],步长: 10, 默认值是该主机当前数据盘大小。 + DiskSpace *int `required:"false"` + + // 系统大小,单位: GB,范围[20,100],步长: 10。 + BootDiskSpace *int `required:"false"` + + // 方舟机型。No,Yes。默认是No。 + TimemachineFeature *string `required:"false"` + + // 网卡升降级(1,表示升级,2表示降级,0表示不变) + NetCapValue *int `required:"false"` + + // 主机系列,目前支持N1,N2 + HostType *string `required:"false"` +} + +// GetUHostUpgradePriceResponse is response schema for GetUHostUpgradePrice action +type GetUHostUpgradePriceResponse struct { + response.CommonBase + + // 升级差价 + Price float64 +} + +// NewGetUHostUpgradePriceRequest will create request of GetUHostUpgradePrice action. +func (c *UHostClient) NewGetUHostUpgradePriceRequest() *GetUHostUpgradePriceRequest { + req := &GetUHostUpgradePriceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// GetUHostUpgradePrice - 获取UHost实例升级配置的价格。 +func (c *UHostClient) GetUHostUpgradePrice(req *GetUHostUpgradePriceRequest) (*GetUHostUpgradePriceResponse, error) { + var err error + var res GetUHostUpgradePriceResponse + + err = c.client.InvokeAction("GetUHostUpgradePrice", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/modify_uhost_instance_name.go b/services/uhost/modify_uhost_instance_name.go new file mode 100644 index 00000000..c66d6a46 --- /dev/null +++ b/services/uhost/modify_uhost_instance_name.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost ModifyUHostInstanceName + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ModifyUHostInstanceNameRequest is request schema for ModifyUHostInstanceName action +type ModifyUHostInstanceNameRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` + + // UHost实例名称 + Name *string `required:"false"` +} + +// ModifyUHostInstanceNameResponse is response schema for ModifyUHostInstanceName action +type ModifyUHostInstanceNameResponse struct { + response.CommonBase + + // UHost实例ID + UhostId string +} + +// NewModifyUHostInstanceNameRequest will create request of ModifyUHostInstanceName action. +func (c *UHostClient) NewModifyUHostInstanceNameRequest() *ModifyUHostInstanceNameRequest { + req := &ModifyUHostInstanceNameRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ModifyUHostInstanceName - 修改指定UHost实例名称,需要给出数据中心,UHostId,及新的实例名称。 +func (c *UHostClient) ModifyUHostInstanceName(req *ModifyUHostInstanceNameRequest) (*ModifyUHostInstanceNameResponse, error) { + var err error + var res ModifyUHostInstanceNameResponse + + err = c.client.InvokeAction("ModifyUHostInstanceName", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/modify_uhost_instance_remark.go b/services/uhost/modify_uhost_instance_remark.go new file mode 100644 index 00000000..6d9019f5 --- /dev/null +++ b/services/uhost/modify_uhost_instance_remark.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost ModifyUHostInstanceRemark + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ModifyUHostInstanceRemarkRequest is request schema for ModifyUHostInstanceRemark action +type ModifyUHostInstanceRemarkRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` + + // 备注 + Remark *string `required:"false"` +} + +// ModifyUHostInstanceRemarkResponse is response schema for ModifyUHostInstanceRemark action +type ModifyUHostInstanceRemarkResponse struct { + response.CommonBase + + // UHost实例ID + UhostId string +} + +// NewModifyUHostInstanceRemarkRequest will create request of ModifyUHostInstanceRemark action. +func (c *UHostClient) NewModifyUHostInstanceRemarkRequest() *ModifyUHostInstanceRemarkRequest { + req := &ModifyUHostInstanceRemarkRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ModifyUHostInstanceRemark - 修改指定UHost实例备注信息。 +func (c *UHostClient) ModifyUHostInstanceRemark(req *ModifyUHostInstanceRemarkRequest) (*ModifyUHostInstanceRemarkResponse, error) { + var err error + var res ModifyUHostInstanceRemarkResponse + + err = c.client.InvokeAction("ModifyUHostInstanceRemark", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/modify_uhost_instance_tag.go b/services/uhost/modify_uhost_instance_tag.go new file mode 100644 index 00000000..b2da020e --- /dev/null +++ b/services/uhost/modify_uhost_instance_tag.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost ModifyUHostInstanceTag + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ModifyUHostInstanceTagRequest is request schema for ModifyUHostInstanceTag action +type ModifyUHostInstanceTagRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` + + // 业务组名称 + Tag *string `required:"false"` +} + +// ModifyUHostInstanceTagResponse is response schema for ModifyUHostInstanceTag action +type ModifyUHostInstanceTagResponse struct { + response.CommonBase + + // UHost实例ID + UhostId string +} + +// NewModifyUHostInstanceTagRequest will create request of ModifyUHostInstanceTag action. +func (c *UHostClient) NewModifyUHostInstanceTagRequest() *ModifyUHostInstanceTagRequest { + req := &ModifyUHostInstanceTagRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ModifyUHostInstanceTag - 修改指定UHost实例业务组标识。 +func (c *UHostClient) ModifyUHostInstanceTag(req *ModifyUHostInstanceTagRequest) (*ModifyUHostInstanceTagResponse, error) { + var err error + var res ModifyUHostInstanceTagResponse + + err = c.client.InvokeAction("ModifyUHostInstanceTag", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/poweroff_uhost_instance.go b/services/uhost/poweroff_uhost_instance.go new file mode 100644 index 00000000..476ca63a --- /dev/null +++ b/services/uhost/poweroff_uhost_instance.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost PoweroffUHostInstance + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// PoweroffUHostInstanceRequest is request schema for PoweroffUHostInstance action +type PoweroffUHostInstanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](./describe_uhost_instance.html) + UHostId *string `required:"true"` +} + +// PoweroffUHostInstanceResponse is response schema for PoweroffUHostInstance action +type PoweroffUHostInstanceResponse struct { + response.CommonBase + + // UHost实例ID + UhostId string +} + +// NewPoweroffUHostInstanceRequest will create request of PoweroffUHostInstance action. +func (c *UHostClient) NewPoweroffUHostInstanceRequest() *PoweroffUHostInstanceRequest { + req := &PoweroffUHostInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// PoweroffUHostInstance - 直接关闭UHost实例电源,无需等待实例正常关闭。 +func (c *UHostClient) PoweroffUHostInstance(req *PoweroffUHostInstanceRequest) (*PoweroffUHostInstanceResponse, error) { + var err error + var res PoweroffUHostInstanceResponse + + err = c.client.InvokeAction("PoweroffUHostInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/reboot_uhost_instance.go b/services/uhost/reboot_uhost_instance.go new file mode 100644 index 00000000..0b000b1c --- /dev/null +++ b/services/uhost/reboot_uhost_instance.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost RebootUHostInstance + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// RebootUHostInstanceRequest is request schema for RebootUHostInstance action +type RebootUHostInstanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` + + // 加密盘密码 + DiskPassword *string `required:"false"` +} + +// RebootUHostInstanceResponse is response schema for RebootUHostInstance action +type RebootUHostInstanceResponse struct { + response.CommonBase + + // UHost实例ID + UhostId string +} + +// NewRebootUHostInstanceRequest will create request of RebootUHostInstance action. +func (c *UHostClient) NewRebootUHostInstanceRequest() *RebootUHostInstanceRequest { + req := &RebootUHostInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// RebootUHostInstance - 重新启动UHost实例,需要指定数据中心及UHostID两个参数的值。 +func (c *UHostClient) RebootUHostInstance(req *RebootUHostInstanceRequest) (*RebootUHostInstanceResponse, error) { + var err error + var res RebootUHostInstanceResponse + + err = c.client.InvokeAction("RebootUHostInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/reinstall_uhost_instance.go b/services/uhost/reinstall_uhost_instance.go new file mode 100644 index 00000000..5349592a --- /dev/null +++ b/services/uhost/reinstall_uhost_instance.go @@ -0,0 +1,68 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost ReinstallUHostInstance + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ReinstallUHostInstanceRequest is request schema for ReinstallUHostInstance action +type ReinstallUHostInstanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例资源ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` + + // 如果创建UHost实例时LoginMode为Password,则必须填写,如果LoginMode为KeyPair,不需要填写 (密码格式使用BASE64编码;LoginMode不可变更) + Password *string `required:"false"` + + // 镜像Id,默认使用原镜像 参见 [DescribeImage](describe_image.html) + ImageId *string `required:"false"` + + // 是否保留数据盘,保留:Yes,不报留:No, 默认:Yes;如果是从Windows重装为Linux或反之,则无法保留数据盘 + ReserveDisk *string `required:"false"` + + // 云灾备指明191 + ResourceType *int `required:"false"` + + // 针对非私有子网主机,可自定义DNS。n可为0-2 + DNSServers []string `required:"false"` +} + +// ReinstallUHostInstanceResponse is response schema for ReinstallUHostInstance action +type ReinstallUHostInstanceResponse struct { + response.CommonBase + + // UHost实例资源ID + UhostId string +} + +// NewReinstallUHostInstanceRequest will create request of ReinstallUHostInstance action. +func (c *UHostClient) NewReinstallUHostInstanceRequest() *ReinstallUHostInstanceRequest { + req := &ReinstallUHostInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ReinstallUHostInstance - 重新安装指定UHost实例的操作系统 +func (c *UHostClient) ReinstallUHostInstance(req *ReinstallUHostInstanceRequest) (*ReinstallUHostInstanceResponse, error) { + var err error + var res ReinstallUHostInstanceResponse + + err = c.client.InvokeAction("ReinstallUHostInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/reset_uhost_instance_password.go b/services/uhost/reset_uhost_instance_password.go new file mode 100644 index 00000000..e46872b9 --- /dev/null +++ b/services/uhost/reset_uhost_instance_password.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost ResetUHostInstancePassword + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ResetUHostInstancePasswordRequest is request schema for ResetUHostInstancePassword action +type ResetUHostInstancePasswordRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID + UHostId *string `required:"true"` + + // UHost新密码(密码格式使用BASE64编码) + Password *string `required:"true"` +} + +// ResetUHostInstancePasswordResponse is response schema for ResetUHostInstancePassword action +type ResetUHostInstancePasswordResponse struct { + response.CommonBase + + // UHost实例ID + UhostId string +} + +// NewResetUHostInstancePasswordRequest will create request of ResetUHostInstancePassword action. +func (c *UHostClient) NewResetUHostInstancePasswordRequest() *ResetUHostInstancePasswordRequest { + req := &ResetUHostInstancePasswordRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ResetUHostInstancePassword - 重置UHost实例的管理员密码。 +func (c *UHostClient) ResetUHostInstancePassword(req *ResetUHostInstancePasswordRequest) (*ResetUHostInstancePasswordResponse, error) { + var err error + var res ResetUHostInstancePasswordResponse + + err = c.client.InvokeAction("ResetUHostInstancePassword", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/resize_uhost_instance.go b/services/uhost/resize_uhost_instance.go new file mode 100644 index 00000000..6497ed2b --- /dev/null +++ b/services/uhost/resize_uhost_instance.go @@ -0,0 +1,68 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost ResizeUHostInstance + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ResizeUHostInstanceRequest is request schema for ResizeUHostInstance action +type ResizeUHostInstanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` + + // 虚拟CPU核数,单位:个,系列1范围:[1,16],系列2范围:[1,32],最小值为1,其他值是2的倍数,默认值为当前实例的CPU核数 + CPU *int `required:"false"` + + // 内存大小,单位:MB,范围[2048,131072],步长:2048,默认值为当前实例的内存大小(BGP-C数据中心最小支持1024,限Linux系统) + Memory *int `required:"false"` + + // 数据盘大小,单位:GB,范围[10,1000]; SSD机型,单位:GB,范围[100,500];步长:10,默认值为当前实例的数据盘大小,数据盘不支持缩容,因此不允许输入比当前实例数据盘大小的值 + DiskSpace *int `required:"false"` + + // 系统盘大小,单位:GB,范围[20,100],步长:10,系统盘不支持缩容,因此不允许输入比当前实例系统盘小的值 + BootDiskSpace *int `required:"false"` + + // 网卡升降级(1,表示升级,2表示降级,0表示不变) + NetCapValue *int `required:"false"` +} + +// ResizeUHostInstanceResponse is response schema for ResizeUHostInstance action +type ResizeUHostInstanceResponse struct { + response.CommonBase + + // UHost实例ID + UhostId string +} + +// NewResizeUHostInstanceRequest will create request of ResizeUHostInstance action. +func (c *UHostClient) NewResizeUHostInstanceRequest() *ResizeUHostInstanceRequest { + req := &ResizeUHostInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ResizeUHostInstance - 修改指定UHost实例的资源配置,如CPU核心数,内存容量大小,磁盘空间大小,网络增强等。 +func (c *UHostClient) ResizeUHostInstance(req *ResizeUHostInstanceRequest) (*ResizeUHostInstanceResponse, error) { + var err error + var res ResizeUHostInstanceResponse + + err = c.client.InvokeAction("ResizeUHostInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/start_uhost_instance.go b/services/uhost/start_uhost_instance.go new file mode 100644 index 00000000..886eda96 --- /dev/null +++ b/services/uhost/start_uhost_instance.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost StartUHostInstance + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// StartUHostInstanceRequest is request schema for StartUHostInstance action +type StartUHostInstanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` + + // 加密盘密码 + DiskPassword *string `required:"false"` +} + +// StartUHostInstanceResponse is response schema for StartUHostInstance action +type StartUHostInstanceResponse struct { + response.CommonBase + + // UHost实例ID + UhostId string +} + +// NewStartUHostInstanceRequest will create request of StartUHostInstance action. +func (c *UHostClient) NewStartUHostInstanceRequest() *StartUHostInstanceRequest { + req := &StartUHostInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// StartUHostInstance - 启动处于关闭状态的UHost实例,需要指定数据中心及UHostID两个参数的值。 +func (c *UHostClient) StartUHostInstance(req *StartUHostInstanceRequest) (*StartUHostInstanceResponse, error) { + var err error + var res StartUHostInstanceResponse + + err = c.client.InvokeAction("StartUHostInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/stop_uhost_instance.go b/services/uhost/stop_uhost_instance.go new file mode 100644 index 00000000..f33a323f --- /dev/null +++ b/services/uhost/stop_uhost_instance.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost StopUHostInstance + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// StopUHostInstanceRequest is request schema for StopUHostInstance action +type StopUHostInstanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost实例ID 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` +} + +// StopUHostInstanceResponse is response schema for StopUHostInstance action +type StopUHostInstanceResponse struct { + response.CommonBase + + // UHost实例ID + UhostId string +} + +// NewStopUHostInstanceRequest will create request of StopUHostInstance action. +func (c *UHostClient) NewStopUHostInstanceRequest() *StopUHostInstanceRequest { + req := &StopUHostInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// StopUHostInstance - 指停止处于运行状态的UHost实例,需指定数据中心及UhostID。 +func (c *UHostClient) StopUHostInstance(req *StopUHostInstanceRequest) (*StopUHostInstanceResponse, error) { + var err error + var res StopUHostInstanceResponse + + err = c.client.InvokeAction("StopUHostInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/terminate_custom_image.go b/services/uhost/terminate_custom_image.go new file mode 100644 index 00000000..7bc7710b --- /dev/null +++ b/services/uhost/terminate_custom_image.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost TerminateCustomImage + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// TerminateCustomImageRequest is request schema for TerminateCustomImage action +type TerminateCustomImageRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // 自制镜像ID 参见 [DescribeImage](describe_image.html) + ImageId *string `required:"true"` +} + +// TerminateCustomImageResponse is response schema for TerminateCustomImage action +type TerminateCustomImageResponse struct { + response.CommonBase + + // 自制镜像Id + ImageId string +} + +// NewTerminateCustomImageRequest will create request of TerminateCustomImage action. +func (c *UHostClient) NewTerminateCustomImageRequest() *TerminateCustomImageRequest { + req := &TerminateCustomImageRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// TerminateCustomImage - 删除用户自定义镜像 +func (c *UHostClient) TerminateCustomImage(req *TerminateCustomImageRequest) (*TerminateCustomImageResponse, error) { + var err error + var res TerminateCustomImageResponse + + err = c.client.InvokeAction("TerminateCustomImage", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/terminate_uhost_instance.go b/services/uhost/terminate_uhost_instance.go new file mode 100644 index 00000000..34194fae --- /dev/null +++ b/services/uhost/terminate_uhost_instance.go @@ -0,0 +1,65 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost TerminateUHostInstance + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// TerminateUHostInstanceRequest is request schema for TerminateUHostInstance action +type TerminateUHostInstanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // UHost资源Id 参见 [DescribeUHostInstance](describe_uhost_instance.html) + UHostId *string `required:"true"` + + // 是否直接删除,0表示按照原来的逻辑(有回收站权限,则进入回收站),1表示直接删除 + Destroy *int `required:"false"` + + // 是否释放绑定的EIP。yes: 解绑EIP后,并释放;其他值或不填:解绑EIP。 + EIPReleased *string `required:"false"` +} + +// TerminateUHostInstanceResponse is response schema for TerminateUHostInstance action +type TerminateUHostInstanceResponse struct { + response.CommonBase + + // UHost 实例 Id + UHostIds []string + + // 放入回收站:"Yes", 彻底删除:“No” + InRecycle string + + // 主机 ID + UHostId string +} + +// NewTerminateUHostInstanceRequest will create request of TerminateUHostInstance action. +func (c *UHostClient) NewTerminateUHostInstanceRequest() *TerminateUHostInstanceRequest { + req := &TerminateUHostInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// TerminateUHostInstance - 删除指定数据中心的UHost实例。 +func (c *UHostClient) TerminateUHostInstance(req *TerminateUHostInstanceRequest) (*TerminateUHostInstanceResponse, error) { + var err error + var res TerminateUHostInstanceResponse + + err = c.client.InvokeAction("TerminateUHostInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/types_uhost_disk_query.go b/services/uhost/types_uhost_disk_query.go new file mode 100644 index 00000000..1f183e56 --- /dev/null +++ b/services/uhost/types_uhost_disk_query.go @@ -0,0 +1,21 @@ +package uhost + +/* + UHostDisk - + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostDisk struct { + // 磁盘大小,单位GB。 + Size *string `required:"true"` + + // 磁盘类型。枚举值:LOCAL_NORMAL 普通本地盘 | CLOUD_NORMAL 普通云盘 |LOCAL_SSD SSD本地盘 | CLOUD_SSD SSD云盘,默认为LOCAL_NORMAL。磁盘仅支持有限组合,详情请查询控制台。 + Type *string `required:"true"` + + // 是否是系统盘。枚举值:True|False + IsBoot *bool `required:"true"` + + // NONE|DATAARK + BackupType *string `required:"false"` +} diff --git a/services/uhost/types_uhost_disk_set.go b/services/uhost/types_uhost_disk_set.go new file mode 100644 index 00000000..c484a870 --- /dev/null +++ b/services/uhost/types_uhost_disk_set.go @@ -0,0 +1,28 @@ +package uhost + +/* + UHostDiskSet - DescribeUHostInstance + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostDiskSet struct { + + // 磁盘类型。系统盘: Boot,数据盘: Data,网络盘:Udisk + Type string + + // 磁盘ID + DiskId string + + // UDisk名字(仅当磁盘是UDisk时返回) + Name string + + // 磁盘盘符 + Drive string + + // 磁盘大小,单位: GB + Size int + + // 备份类型,DataArk + BackupType string +} diff --git a/services/uhost/types_uhost_image_set.go b/services/uhost/types_uhost_image_set.go new file mode 100644 index 00000000..330ad377 --- /dev/null +++ b/services/uhost/types_uhost_image_set.go @@ -0,0 +1,55 @@ +package uhost + +/* + UHostImageSet - DescribeImage + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostImageSet struct { + + // 镜像ID + ImageId string + + // 镜像名称 + ImageName string + + // 可用区,参见 [可用区列表](../summary/regionlist.html) | + Zone string + + // 操作系统类型:Liunx,Windows + OsType string + + // 操作系统名称 + OsName string + + // 镜像类型 标准镜像:Base, 行业镜像:Business,自定义镜像:Custom + ImageType string + + // 特殊状态标识, 目前只有[NetEnhnced](高包量机型) + Features []string + + // 行业镜像类型(仅行业镜像将返回这个值) + FuncType string + + // 集成软件名称(仅行业镜像将返回这个值) + IntegratedSoftware string + + // 供应商(仅行业镜像将返回这个值) + Vendor string + + // 介绍链接(仅行业镜像将返回这个值) + Links string + + // 镜像状态, 可用:Available,制作中:Making, 不可用:Unavailable + State string + + // 镜像描述 + ImageDescription string + + // 创建时间,格式为Unix时间戳 + CreateTime int + + // 镜像大小 + ImageSize int +} diff --git a/services/uhost/types_uhost_instance_set.go b/services/uhost/types_uhost_instance_set.go new file mode 100644 index 00000000..aa92313f --- /dev/null +++ b/services/uhost/types_uhost_instance_set.go @@ -0,0 +1,109 @@ +package uhost + +/* + UHostInstanceSet - DescribeUHostInstance + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostInstanceSet struct { + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone string + + // UHost实例ID + UHostId string + + // UHost类型,枚举为:N1:标准型系列1;N2:标准型系列2 ;I1:高IO型系列1;I2:高IO型系列2;D1:大数据型系列1;G1:GPU型系列1;G2:GPU型系列2;G3:GPU型系列2 + UHostType string + + // 系统盘与数据盘的磁盘类型。 枚举值为:LocalDisk,本地磁盘; UDisk,云硬盘 + StorageType string + + // 镜像ID + ImageId string + + // 基础镜像ID(指当前自定义镜像的来源镜像) + BasicImageId string + + // 基础镜像名称(指当前自定义镜像的来源镜像) + BasicImageName string + + // 业务组名称 + Tag string + + // 备注 + Remark string + + // UHost实例名称 + Name string + + // 实例状态, 初始化: Initializing; 启动中: Starting; 运行中: Running; 关机中: Stopping; 关机: Stopped 安装失败: Install Fail; 重启中: Rebooting + State string + + // 创建时间,格式为Unix时间戳 + CreateTime int + + // 计费模式,枚举值为: Year,按年付费; Month,按月付费; Dynamic,按需付费(需开启权限); + ChargeType string + + // 到期时间,格式为Unix时间戳 + ExpireTime int + + // 虚拟CPU核数,单位: 个 + CPU int + + // 内存大小,单位: MB + Memory int + + // 是否自动续费,自动续费:“Yes”,不自动续费:“No” + AutoRenew string + + // 磁盘信息见 UHostDiskSet + DiskSet []UHostDiskSet + + // 详细信息见 UHostIPSet + IPSet []UHostIPSet + + // 网络增强。目前仅支持Normal和Super + NetCapability string + + // 网络状态 连接:Connected, 断开:NotConnected + NetworkState string + + // yes: 开启方舟; no,未开启方舟 + TimemachineFeature string + + // true: 开启热升级; false,未开启热升级 + HotplugFeature bool + + // 基础网络:Default;子网:Private + SubnetType string + + // 内网或者子网的IP地址 + IPs []string + + // Os名称 + OsName string + + // "Linux"或者"Windows" + OsType string + + // 删除时间,格式为Unix时间戳 + DeleteTime int + + // 主机系列:N2,表示系列2;N1,表示系列1 + HostType string + + // 主机的生命周期类型。目前仅支持Normal:普通; + LifeCycle string + + // 主机的 GPU 数量 + GPU int + + // 系统盘状态 Normal: 已初始化完成 + BootDiskState string + + // 主机的存储空间 + TotalDiskSpace int +} diff --git a/services/uhost/types_uhost_ipset.go b/services/uhost/types_uhost_ipset.go new file mode 100644 index 00000000..6608f6df --- /dev/null +++ b/services/uhost/types_uhost_ipset.go @@ -0,0 +1,22 @@ +package uhost + +/* + UHostIPSet - DescribeUHostInstance + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostIPSet struct { + + // 电信: China-telecom,联通: China-unicom, 国际: Internation,BGP: Bgp,内网: Private 双线: Duplet + Type string + + // IP资源ID (内网IP无对应的资源ID) + IPId string + + // IP地址 + IP string + + // IP对应的带宽, 单位: Mb (内网IP不显示带宽信息) + Bandwidth int +} diff --git a/services/uhost/types_uhost_price_set.go b/services/uhost/types_uhost_price_set.go new file mode 100644 index 00000000..de93d140 --- /dev/null +++ b/services/uhost/types_uhost_price_set.go @@ -0,0 +1,16 @@ +package uhost + +/* + UHostPriceSet - 主机价格 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostPriceSet struct { + + // 计费类型。Year,Month,Dynamic + ChargeType string + + // 价格,单位: 元,保留小数点后两位有效数字 + Price float64 +} diff --git a/services/uhost/types_uhost_tag_set.go b/services/uhost/types_uhost_tag_set.go new file mode 100644 index 00000000..7eceabcb --- /dev/null +++ b/services/uhost/types_uhost_tag_set.go @@ -0,0 +1,19 @@ +package uhost + +/* + UHostTagSet - DescribeUHostTags + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UHostTagSet struct { + + // 业务组名称 + Tag string + + // 该业务组中包含的主机个数 + TotalCount int + + // 可用区 + Zone string +} diff --git a/services/uhost/upgrade_to_ark_uhost_instance.go b/services/uhost/upgrade_to_ark_uhost_instance.go new file mode 100644 index 00000000..2db25d0e --- /dev/null +++ b/services/uhost/upgrade_to_ark_uhost_instance.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UHost UpgradeToArkUHostInstance + +package uhost + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// UpgradeToArkUHostInstanceRequest is request schema for UpgradeToArkUHostInstance action +type UpgradeToArkUHostInstanceRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"true"` + + // UHost主机的资源ID,例如UHostIds.0代表希望升级的主机1,UHostIds.1代表主机2。 + UHostIds []string `required:"true"` + + // 代金券ID 请参考DescribeCoupon接口 + CouponId *string `required:"false"` +} + +// UpgradeToArkUHostInstanceResponse is response schema for UpgradeToArkUHostInstance action +type UpgradeToArkUHostInstanceResponse struct { + response.CommonBase + + // UHost主机的资源ID数组 + UHostSet []string +} + +// NewUpgradeToArkUHostInstanceRequest will create request of UpgradeToArkUHostInstance action. +func (c *UHostClient) NewUpgradeToArkUHostInstanceRequest() *UpgradeToArkUHostInstanceRequest { + req := &UpgradeToArkUHostInstanceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// UpgradeToArkUHostInstance - 普通升级为方舟机型 +func (c *UHostClient) UpgradeToArkUHostInstance(req *UpgradeToArkUHostInstanceRequest) (*UpgradeToArkUHostInstanceResponse, error) { + var err error + var res UpgradeToArkUHostInstanceResponse + + err = c.client.InvokeAction("UpgradeToArkUHostInstance", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/uhost/wait_until_uhost_instance_state.go b/services/uhost/wait_until_uhost_instance_state.go new file mode 100644 index 00000000..c8860e85 --- /dev/null +++ b/services/uhost/wait_until_uhost_instance_state.go @@ -0,0 +1,70 @@ +package uhost + +import ( + "time" + + "github.com/ucloud/ucloud-sdk-go/private/utils" + "github.com/ucloud/ucloud-sdk-go/ucloud" + uerr "github.com/ucloud/ucloud-sdk-go/ucloud/error" + "github.com/ucloud/ucloud-sdk-go/ucloud/log" + "github.com/ucloud/ucloud-sdk-go/ucloud/request" +) + +type WaitUntilUHostInstanceStateRequest struct { + request.CommonBase + + Interval *time.Duration + MaxAttempts *int + DescribeRequest *DescribeUHostInstanceRequest + State State + IgnoreError *bool +} + +// NewWaitUntilUHostInstanceStateRequest will create request of WaitUntilUHostInstanceState action. +func (c *UHostClient) NewWaitUntilUHostInstanceStateRequest() *WaitUntilUHostInstanceStateRequest { + cfg := c.client.GetConfig() + + return &WaitUntilUHostInstanceStateRequest{ + CommonBase: request.CommonBase{ + Region: ucloud.String(cfg.Region), + ProjectId: ucloud.String(cfg.ProjectId), + }, + } +} + +// WaitUntilUHostInstanceState will pending current goroutine until the state has changed to expected state. +func (c *UHostClient) WaitUntilUHostInstanceState(req *WaitUntilUHostInstanceStateRequest) error { + waiter := utils.FuncWaiter{ + Interval: ucloud.TimeDurationValue(req.Interval), + MaxAttempts: ucloud.IntValue(req.MaxAttempts), + IgnoreError: ucloud.BoolValue(req.IgnoreError), + Checker: func() (bool, error) { + resp, err := c.DescribeUHostInstance(req.DescribeRequest) + + if err != nil { + skipErrors := []string{uerr.ErrNetwork, uerr.ErrHTTPStatus, uerr.ErrRetCode} + if uErr, ok := err.(uerr.Error); ok && utils.IsStringIn(uErr.Name(), skipErrors) { + log.Infof("skip error for wait resource state, %s", uErr) + return false, nil + } + log.Infof("wait for resource state is ready, %s", err) + return false, err + } + + // TODO: Ensure if it is any data consistency problem? + // Such as creating a new uhost, but cannot describe it's correct state immediately ... + for _, uhost := range resp.UHostSet { + if val, _ := req.State.MarshalValue(); uhost.State != val { + return false, nil + } + } + + if len(resp.UHostSet) > 0 { + return true, nil + } else { + return false, nil + } + }, + } + return waiter.WaitForCompletion() +} diff --git a/services/ulb/allocate_backend.go b/services/ulb/allocate_backend.go new file mode 100644 index 00000000..109438f8 --- /dev/null +++ b/services/ulb/allocate_backend.go @@ -0,0 +1,65 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB AllocateBackend + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// AllocateBackendRequest is request schema for AllocateBackend action +type AllocateBackendRequest struct { + request.CommonBase + + // 负载均衡实例的ID + ULBId *string `required:"true"` + + // VServer实例的ID + VServerId *string `required:"true"` + + // 所添加的后端资源的类型,枚举值:UHost -> 云主机;UPM -> 物理云主机; UDHost -> 私有专区主机;UDocker -> 容器,默认值为“UHost” + ResourceType *string `required:"true"` + + // 所添加的后端资源的资源ID + ResourceId *string `required:"true"` + + // 所添加的后端资源服务端口,取值范围[1-65535],默认80 + Port *int `required:"false"` + + // 后端实例状态开关,枚举值: 1:启用; 0:禁用 默认为启用 + Enabled *int `required:"false"` +} + +// AllocateBackendResponse is response schema for AllocateBackend action +type AllocateBackendResponse struct { + response.CommonBase + + // 所添加的后端资源在ULB中的对象ID,(为ULB系统中使用,与资源自身ID无关),可用于 UpdateBackendAttribute/UpdateBackendAttributeBatch/ReleaseBackend + BackendId string +} + +// NewAllocateBackendRequest will create request of AllocateBackend action. +func (c *ULBClient) NewAllocateBackendRequest() *AllocateBackendRequest { + req := &AllocateBackendRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// AllocateBackend - 添加ULB后端资源实例 +func (c *ULBClient) AllocateBackend(req *AllocateBackendRequest) (*AllocateBackendResponse, error) { + var err error + var res AllocateBackendResponse + + err = c.client.InvokeAction("AllocateBackend", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/allocate_backend_batch.go b/services/ulb/allocate_backend_batch.go new file mode 100644 index 00000000..9301474a --- /dev/null +++ b/services/ulb/allocate_backend_batch.go @@ -0,0 +1,59 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB AllocateBackendBatch + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// AllocateBackendBatchRequest is request schema for AllocateBackendBatch action +type AllocateBackendBatchRequest struct { + request.CommonBase + + // 负载均衡实例的ID + ULBId *string `required:"true"` + + // VServer实例的ID + VServerId *string `required:"true"` + + // 用| 分割字段,格式:ResourceId| ResourceType| Port| Enabled|IP。ResourceId:所添加的后端资源的资源ID;ResourceType:所添加的后端资源的类型,枚举值:UHost -> 云主机;UPM -> 物理云主机; UDHost -> 私有专区主机;UDocker -> 容器,默认值为“UHost”;Port:所添加的后端资源服务端口,取值范围[1-65535];Enabled:后端实例状态开关,枚举值: 1:启用; 0:禁用;IP:后端资源内网ip; + Backends []string `required:"true"` + + // 已弃用,指定 Api 版本 + ApiVersion *int `required:"false"` +} + +// AllocateBackendBatchResponse is response schema for AllocateBackendBatch action +type AllocateBackendBatchResponse struct { + response.CommonBase + + // 所添加的后端资源ID,(为ULB系统中使用,与资源自身ID无关),可用于 UpdateBackendAttribute/UpdateBackendAttributeBatch/ReleaseBackend + BackendId string +} + +// NewAllocateBackendBatchRequest will create request of AllocateBackendBatch action. +func (c *ULBClient) NewAllocateBackendBatchRequest() *AllocateBackendBatchRequest { + req := &AllocateBackendBatchRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// AllocateBackendBatch - 批量添加VServer后端节点 +func (c *ULBClient) AllocateBackendBatch(req *AllocateBackendBatchRequest) (*AllocateBackendBatchResponse, error) { + var err error + var res AllocateBackendBatchResponse + + err = c.client.InvokeAction("AllocateBackendBatch", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/client.go b/services/ulb/client.go new file mode 100644 index 00000000..648a2b1f --- /dev/null +++ b/services/ulb/client.go @@ -0,0 +1,17 @@ +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type ULBClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *ULBClient { + client := ucloud.NewClient(config, credential) + return &ULBClient{ + client: client, + } +} diff --git a/services/ulb/create_policy.go b/services/ulb/create_policy.go new file mode 100644 index 00000000..f1a21973 --- /dev/null +++ b/services/ulb/create_policy.go @@ -0,0 +1,62 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB CreatePolicy + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreatePolicyRequest is request schema for CreatePolicy action +type CreatePolicyRequest struct { + request.CommonBase + + // 需要添加内容转发策略的负载均衡实例ID + ULBId *string `required:"true"` + + // 需要添加内容转发策略的VServer实例ID + VServerId *string `required:"true"` + + // 内容转发策略应用的后端资源实例的ID,来源于 AllocateBackend 返回的 BackendId + BackendId []string `required:"true"` + + // 内容转发匹配字段 + Match *string `required:"true"` + + // 内容转发匹配字段的类型 + Type *string `required:"false"` +} + +// CreatePolicyResponse is response schema for CreatePolicy action +type CreatePolicyResponse struct { + response.CommonBase + + // 内容转发策略ID + PolicyId string +} + +// NewCreatePolicyRequest will create request of CreatePolicy action. +func (c *ULBClient) NewCreatePolicyRequest() *CreatePolicyRequest { + req := &CreatePolicyRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreatePolicy - 创建VServer内容转发策略 +func (c *ULBClient) CreatePolicy(req *CreatePolicyRequest) (*CreatePolicyResponse, error) { + var err error + var res CreatePolicyResponse + + err = c.client.InvokeAction("CreatePolicy", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/create_ulb.go b/services/ulb/create_ulb.go new file mode 100644 index 00000000..5c41030b --- /dev/null +++ b/services/ulb/create_ulb.go @@ -0,0 +1,74 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB CreateULB + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateULBRequest is request schema for CreateULB action +type CreateULBRequest struct { + request.CommonBase + + // 负载均衡的名字,默认值为“ULB” + ULBName *string `required:"false"` + + // 业务组 + Tag *string `required:"false"` + + // 备注 + Remark *string `required:"false"` + + // 创建的ULB是否为外网模式,默认即为外网模式 + OuterMode *string `required:"false"` + + // 创建的ULB是否为内网模式 + InnerMode *string `required:"false"` + + // 付费方式 + ChargeType *string `required:"false"` + + // ULB所在的VPC的ID, 如果不传则使用默认的VPC + VPCId *string `required:"false"` + + // 内网ULB 所属的子网ID,如果不传则使用默认的子网 + SubnetId *string `required:"false"` + + // ULB 所属的业务组ID,如果不传则使用默认的业务组 + BusinessId *string `required:"false"` +} + +// CreateULBResponse is response schema for CreateULB action +type CreateULBResponse struct { + response.CommonBase + + // 负载均衡实例的Id + ULBId string +} + +// NewCreateULBRequest will create request of CreateULB action. +func (c *ULBClient) NewCreateULBRequest() *CreateULBRequest { + req := &CreateULBRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateULB - 创建负载均衡实例,可以选择内网或者外网 +func (c *ULBClient) CreateULB(req *CreateULBRequest) (*CreateULBResponse, error) { + var err error + var res CreateULBResponse + + err = c.client.InvokeAction("CreateULB", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/create_vserver.go b/services/ulb/create_vserver.go new file mode 100644 index 00000000..279e60a7 --- /dev/null +++ b/services/ulb/create_vserver.go @@ -0,0 +1,83 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB CreateVServer + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateVServerRequest is request schema for CreateVServer action +type CreateVServerRequest struct { + request.CommonBase + + // 负载均衡实例ID + ULBId *string `required:"true"` + + // VServer实例名称,默认为"VServer" + VServerName *string `required:"false"` + + // 监听器类型,枚举值为:RequestProxy -> 请求代理;PacketsTransmit -> 报文转发;默认为"RequestProxy" + ListenType *string `required:"false"` + + // VServer实例的协议,请求代理模式下有 HTTP、HTTPS、TCP,报文转发下有 TCP,UDP。默认为“HTTP" + Protocol *string `required:"false"` + + // VServer后端端口,取值范围[1-65535];默认值为80 + FrontendPort *int `required:"false"` + + // VServer负载均衡模式,枚举值:Roundrobin -> 轮询;Source -> 源地址;ConsistentHash -> 一致性哈希;SourcePort -> 源地址(计算端口);ConsistentHashPort -> 一致性哈希(计算端口)。ConsistentHash,SourcePort,ConsistentHashPort 只在报文转发中使用;Roundrobin和Source在请求代理和报文转发中使用。默认为:"Roundrobin" + Method *string `required:"false"` + + // VServer会话保持方式,默认关闭会话保持。枚举值:None -> 关闭;ServerInsert -> 自动生成KEY;UserDefined -> 用户自定义KEY。 + PersistenceType *string `required:"false"` + + // 根据PersistenceType确认; None和ServerInsert: 此字段无意义; UserDefined:此字段传入自定义会话保持String + PersistenceInfo *string `required:"false"` + + // ListenType为RequestProxy时表示空闲连接的回收时间,单位:秒,取值范围:时(0,86400],默认值为60;ListenType为PacketsTransmit时表示连接保持的时间,单位:秒,取值范围:[60,900],0 表示禁用连接保持 + ClientTimeout *int `required:"false"` + + // 健康检查类型,枚举值:Port -> 端口检查;Path -> 路径检查; + MonitorType *string `required:"false"` + + // 健康检查的域名 + Domain *string `required:"false"` + + // 健康检查的路径 + Path *string `required:"false"` +} + +// CreateVServerResponse is response schema for CreateVServer action +type CreateVServerResponse struct { + response.CommonBase + + // VServer实例的Id + VServerId string +} + +// NewCreateVServerRequest will create request of CreateVServer action. +func (c *ULBClient) NewCreateVServerRequest() *CreateVServerRequest { + req := &CreateVServerRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateVServer - 创建VServer实例,定义监听的协议和端口以及负载均衡算法 +func (c *ULBClient) CreateVServer(req *CreateVServerRequest) (*CreateVServerResponse, error) { + var err error + var res CreateVServerResponse + + err = c.client.InvokeAction("CreateVServer", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/delete_policy.go b/services/ulb/delete_policy.go new file mode 100644 index 00000000..fd0ed2f9 --- /dev/null +++ b/services/ulb/delete_policy.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB DeletePolicy + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeletePolicyRequest is request schema for DeletePolicy action +type DeletePolicyRequest struct { + request.CommonBase + + // 内容转发策略ID + PolicyId *string `required:"true"` + + // 内容转发策略组ID + GroupId *string `required:"false"` + + // VServer 资源ID + VServerId *string `required:"false"` +} + +// DeletePolicyResponse is response schema for DeletePolicy action +type DeletePolicyResponse struct { + response.CommonBase +} + +// NewDeletePolicyRequest will create request of DeletePolicy action. +func (c *ULBClient) NewDeletePolicyRequest() *DeletePolicyRequest { + req := &DeletePolicyRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DeletePolicy - 删除内容转发策略 +func (c *ULBClient) DeletePolicy(req *DeletePolicyRequest) (*DeletePolicyResponse, error) { + var err error + var res DeletePolicyResponse + + err = c.client.InvokeAction("DeletePolicy", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/delete_ulb.go b/services/ulb/delete_ulb.go new file mode 100644 index 00000000..3d8edb91 --- /dev/null +++ b/services/ulb/delete_ulb.go @@ -0,0 +1,47 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB DeleteULB + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeleteULBRequest is request schema for DeleteULB action +type DeleteULBRequest struct { + request.CommonBase + + // 负载均衡实例的ID + ULBId *string `required:"true"` +} + +// DeleteULBResponse is response schema for DeleteULB action +type DeleteULBResponse struct { + response.CommonBase +} + +// NewDeleteULBRequest will create request of DeleteULB action. +func (c *ULBClient) NewDeleteULBRequest() *DeleteULBRequest { + req := &DeleteULBRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DeleteULB - 删除负载均衡实例 +func (c *ULBClient) DeleteULB(req *DeleteULBRequest) (*DeleteULBResponse, error) { + var err error + var res DeleteULBResponse + + err = c.client.InvokeAction("DeleteULB", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/delete_vserver.go b/services/ulb/delete_vserver.go new file mode 100644 index 00000000..34567882 --- /dev/null +++ b/services/ulb/delete_vserver.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB DeleteVServer + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeleteVServerRequest is request schema for DeleteVServer action +type DeleteVServerRequest struct { + request.CommonBase + + // 负载均衡实例的ID + ULBId *string `required:"true"` + + // VServer实例的ID + VServerId *string `required:"true"` +} + +// DeleteVServerResponse is response schema for DeleteVServer action +type DeleteVServerResponse struct { + response.CommonBase +} + +// NewDeleteVServerRequest will create request of DeleteVServer action. +func (c *ULBClient) NewDeleteVServerRequest() *DeleteVServerRequest { + req := &DeleteVServerRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DeleteVServer - 删除VServer实例 +func (c *ULBClient) DeleteVServer(req *DeleteVServerRequest) (*DeleteVServerResponse, error) { + var err error + var res DeleteVServerResponse + + err = c.client.InvokeAction("DeleteVServer", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/describe_ulb.go b/services/ulb/describe_ulb.go new file mode 100644 index 00000000..e1237200 --- /dev/null +++ b/services/ulb/describe_ulb.go @@ -0,0 +1,68 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB DescribeULB + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeULBRequest is request schema for DescribeULB action +type DescribeULBRequest struct { + request.CommonBase + + // 数据偏移量,默认为0 + Offset *int `required:"false"` + + // 数据分页值,默认为20 + Limit *int `required:"false"` + + // 负载均衡实例的Id。 若指定则返回指定的负载均衡实例的信息; 若不指定则返回当前数据中心中所有的负载均衡实例的信息 + ULBId *string `required:"false"` + + // ULB所属的VPC + VPCId *string `required:"false"` + + // ULB所属的子网ID + SubnetId *string `required:"false"` + + // ULB所属的业务组ID + BusinessId *string `required:"false"` +} + +// DescribeULBResponse is response schema for DescribeULB action +type DescribeULBResponse struct { + response.CommonBase + + // 满足条件的ULB总数 + TotalCount int + + // ULB列表,每项参数详见 ULBSet + DataSet []ULBSet +} + +// NewDescribeULBRequest will create request of DescribeULB action. +func (c *ULBClient) NewDescribeULBRequest() *DescribeULBRequest { + req := &DescribeULBRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeULB - 获取ULB详细信息 +func (c *ULBClient) DescribeULB(req *DescribeULBRequest) (*DescribeULBResponse, error) { + var err error + var res DescribeULBResponse + + err = c.client.InvokeAction("DescribeULB", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/describe_vserver.go b/services/ulb/describe_vserver.go new file mode 100644 index 00000000..9ac69bc6 --- /dev/null +++ b/services/ulb/describe_vserver.go @@ -0,0 +1,62 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB DescribeVServer + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeVServerRequest is request schema for DescribeVServer action +type DescribeVServerRequest struct { + request.CommonBase + + // 负载均衡实例的Id + ULBId *string `required:"true"` + + // VServer实例的Id;若指定则返回指定的VServer实例的信息; 若不指定则返回当前负载均衡实例下所有VServer的信息 + VServerId *string `required:"false"` + + // 数据分页值 + Limit *string `required:"false"` + + // 数据偏移量 + Offset *string `required:"false"` +} + +// DescribeVServerResponse is response schema for DescribeVServer action +type DescribeVServerResponse struct { + response.CommonBase + + // 满足条件的VServer总数 + TotalCount int + + // VServer列表,每项参数详见 ULBVServerSet + DataSet []ULBVServerSet +} + +// NewDescribeVServerRequest will create request of DescribeVServer action. +func (c *ULBClient) NewDescribeVServerRequest() *DescribeVServerRequest { + req := &DescribeVServerRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeVServer - 获取ULB下的VServer的详细信息 +func (c *ULBClient) DescribeVServer(req *DescribeVServerRequest) (*DescribeVServerResponse, error) { + var err error + var res DescribeVServerResponse + + err = c.client.InvokeAction("DescribeVServer", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/doc.go b/services/ulb/doc.go new file mode 100644 index 00000000..6499e334 --- /dev/null +++ b/services/ulb/doc.go @@ -0,0 +1,11 @@ +/* + Package ulb include resources of ucloud ulb product + + See also + + - API: https://docs.ucloud.cn/api/ulb-api/index + - Product: https://www.ucloud.cn/site/product/ulb.html + + for detail. +*/ +package ulb diff --git a/services/ulb/release_backend.go b/services/ulb/release_backend.go new file mode 100644 index 00000000..91fae690 --- /dev/null +++ b/services/ulb/release_backend.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB ReleaseBackend + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ReleaseBackendRequest is request schema for ReleaseBackend action +type ReleaseBackendRequest struct { + request.CommonBase + + // 负载均衡实例的ID + ULBId *string `required:"true"` + + // 后端资源实例的ID(ULB后端ID,非资源自身ID) + BackendId *string `required:"true"` +} + +// ReleaseBackendResponse is response schema for ReleaseBackend action +type ReleaseBackendResponse struct { + response.CommonBase +} + +// NewReleaseBackendRequest will create request of ReleaseBackend action. +func (c *ULBClient) NewReleaseBackendRequest() *ReleaseBackendRequest { + req := &ReleaseBackendRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ReleaseBackend - 从VServer释放后端资源实例 +func (c *ULBClient) ReleaseBackend(req *ReleaseBackendRequest) (*ReleaseBackendResponse, error) { + var err error + var res ReleaseBackendResponse + + err = c.client.InvokeAction("ReleaseBackend", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/types_policy_backend_set.go b/services/ulb/types_policy_backend_set.go new file mode 100644 index 00000000..049eeb5f --- /dev/null +++ b/services/ulb/types_policy_backend_set.go @@ -0,0 +1,25 @@ +package ulb + +/* + PolicyBackendSet - 内容转发下rs详细信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type PolicyBackendSet struct { + + // 所添加的后端资源在ULB中的对象ID,(为ULB系统中使用,与资源自身ID无关 + BackendId string + + // 后端资源的对象ID + ObjectId string + + // 所添加的后端资源服务端口 + Port int + + // 后端资源的内网IP + PrivateIP string + + // 后端资源的实例名称 + ResourceName string +} diff --git a/services/ulb/types_ulb_policy_backend_set.go b/services/ulb/types_ulb_policy_backend_set.go new file mode 100644 index 00000000..89bc5121 --- /dev/null +++ b/services/ulb/types_ulb_policy_backend_set.go @@ -0,0 +1,19 @@ +package ulb + +/* + UlbPolicyBackendSet - DescribePolicyGroup + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UlbPolicyBackendSet struct { + + // 后端资源实例的ID + BackendId string + + // 后端资源实例的内网IP + PrivateIP string + + // 后端资源实例的服务端口 + Port int +} diff --git a/services/ulb/types_ulb_policy_group_set.go b/services/ulb/types_ulb_policy_group_set.go new file mode 100644 index 00000000..87b7cd78 --- /dev/null +++ b/services/ulb/types_ulb_policy_group_set.go @@ -0,0 +1,19 @@ +package ulb + +/* + UlbPolicyGroupSet - DescribePolicyGroup + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UlbPolicyGroupSet struct { + + // 内容转发策略组ID + GroupId string + + // 内容转发策略组名称 + GroupName string + + // 内容转发策略组详细信息,具体结构见 UlbPolicySet + PolicySet []UlbPolicySet +} diff --git a/services/ulb/types_ulb_policy_set.go b/services/ulb/types_ulb_policy_set.go new file mode 100644 index 00000000..06c2ac53 --- /dev/null +++ b/services/ulb/types_ulb_policy_set.go @@ -0,0 +1,25 @@ +package ulb + +/* + UlbPolicySet - DescribePolicyGroup + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UlbPolicySet struct { + + // 内容转发策略组ID + PolicyId string + + // 内容转发匹配字段的类型,当前只支持按域名转发。枚举值为: Domain,按域名转发 + Type string + + // 内容转发匹配字段 + Match string + + // 内容转发策略组ID应用的VServer实例的ID + VServerId string + + // 内容转发策略组ID所应用的后端资源列表,具体结构见 UlbPolicyBackendSet + BackendSet []UlbPolicyBackendSet +} diff --git a/services/ulb/types_ulbbackend_set.go b/services/ulb/types_ulbbackend_set.go new file mode 100644 index 00000000..2e39b99c --- /dev/null +++ b/services/ulb/types_ulbbackend_set.go @@ -0,0 +1,37 @@ +package ulb + +/* + ULBBackendSet - DescribeULB + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBBackendSet struct { + + // 后端资源实例的Id + BackendId string + + // 后端资源实例的类型 + ResourceType string + + // 后端资源实例的资源Id + ResourceId string + + // 后端资源实例的资源名字 + ResourceName string + + // 后端资源实例的内网IP + PrivateIP string + + // 后端资源实例服务的端口 + Port int + + // 后端资源实例的启用与否 + Enabled int + + // 后端资源实例的运行状态 + Status int + + // 后端资源实例的资源所在的子网的ID + SubnetId string +} diff --git a/services/ulb/types_ulbipset.go b/services/ulb/types_ulbipset.go new file mode 100644 index 00000000..521089ce --- /dev/null +++ b/services/ulb/types_ulbipset.go @@ -0,0 +1,19 @@ +package ulb + +/* + ULBIPSet - DescribeULB + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBIPSet struct { + + // 弹性IP的运营商信息,枚举值为: Bgp:BGP IP International:国际IP + OperatorName string + + // 弹性IP地址 + EIP string + + // 弹性IP的ID + EIPId string +} diff --git a/services/ulb/types_ulbpolicy_set.go b/services/ulb/types_ulbpolicy_set.go new file mode 100644 index 00000000..b88e8efe --- /dev/null +++ b/services/ulb/types_ulbpolicy_set.go @@ -0,0 +1,34 @@ +package ulb + +/* + ULBPolicySet - 内容转发详细列表 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBPolicySet struct { + + // 内容转发Id,默认内容转发类型下为空。 + PolicyId string + + // 内容类型,枚举值:Custom -> 客户自定义;Default -> 默认内容转发 + PolicyType string + + // 内容转发匹配字段的类型,枚举值:Domain -> 域名;Path -> 路径; 默认内容转发类型下为空 + Type string + + // 内容转发匹配字段;默认内容转发类型下为空。 + Match string + + // 内容转发优先级,范围[1,9999],数字越大优先级越高。默认内容转发规则下为0。 + PolicyPriority int + + // 所属VServerId + VServerId string + + // 默认内容转发类型下返回当前rs总数 + TotalCount int + + // 内容转发下rs的详细信息,参考PolicyBackendSet + BackendSet []PolicyBackendSet +} diff --git a/services/ulb/types_ulbset.go b/services/ulb/types_ulbset.go new file mode 100644 index 00000000..5f531049 --- /dev/null +++ b/services/ulb/types_ulbset.go @@ -0,0 +1,61 @@ +package ulb + +/* + ULBSet - DescribeULB + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBSet struct { + + // 负载均衡的资源ID + ULBId string + + // 负载均衡的资源名称(内部记载,废弃) + ULBName string + + // 负载均衡的资源名称(资源系统中),缺省值“ULB” + Name string + + // 负载均衡的业务组名称,缺省值“Default” + Tag string + + // 负载均衡的备注,缺省值“” + Remark string + + // 带宽类型,枚举值为: 0,非共享带宽; 1,共享带宽 + BandwidthType int + + // 带宽 + Bandwidth int + + // ULB的创建时间,格式为Unix Timestamp + CreateTime int + + // ULB的到期时间,格式为Unix Timestamp + ExpireTime int + + // ULB的详细信息列表(废弃) + Resource []string + + // ULB的详细信息列表,具体结构见下方 ULBIPSet + IPSet []ULBIPSet + + // 负载均衡实例中存在的VServer实例列表,具体结构见下方 ULBVServerSet + VServerSet []ULBVServerSet + + // ULB 的类型 + ULBType string + + // ULB所在的VPC的ID + VPCId string + + // ULB 为 InnerMode 时,ULB 所属的子网ID,默认为空 + SubnetId string + + // ULB 所属的业务组ID + BusinessId string + + // ULB的内网IP,当ULBType为OuterMode时,该值为空 + PrivateIP string +} diff --git a/services/ulb/types_ulbsslset.go b/services/ulb/types_ulbsslset.go new file mode 100644 index 00000000..a5ec42a2 --- /dev/null +++ b/services/ulb/types_ulbsslset.go @@ -0,0 +1,16 @@ +package ulb + +/* + ULBSSLSet - DescribeULB + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBSSLSet struct { + + // SSL证书的Id + SSLId string + + // SSL证书的名字 + SSLName string +} diff --git a/services/ulb/types_ulbvserver_set.go b/services/ulb/types_ulbvserver_set.go new file mode 100644 index 00000000..752dd83d --- /dev/null +++ b/services/ulb/types_ulbvserver_set.go @@ -0,0 +1,58 @@ +package ulb + +/* + ULBVServerSet - DescribeULB + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ULBVServerSet struct { + + // VServer实例的Id + VServerId string + + // VServer实例的名字 + VServerName string + + // VServer实例的协议。 枚举值为:HTTP,TCP,UDP,HTTPS。 + Protocol string + + // VServer服务端口 + FrontendPort int + + // VServer负载均衡的模式,枚举值:Roundrobin -> 轮询;Source -> 源地址;ConsistentHash -> 一致性哈希;SourcePort -> 源地址(计算端口);ConsistentHashPort -> 一致性哈希(计算端口)。 + Method string + + // VServer会话保持方式。枚举值为: None -> 关闭会话保持; ServerInsert -> 自动生成; UserDefined -> 用户自定义。 + PersistenceType string + + // 根据PersistenceType确定: None或ServerInsert,此字段为空; UserDefined,此字段展示用户自定义会话string。 + PersistenceInfo string + + // 空闲连接的回收时间,单位:秒。 + ClientTimeout int + + // VServer的运行状态。枚举值: 0 -> rs全部运行正常;1 -> rs部分运行正常;2 -> rs全部运行异常。 + Status int + + // VServer绑定的SSL证书信息,具体结构见下方 ULBSSLSet + SSLSet []ULBSSLSet + + // 后端资源信息列表,具体结构见下方 ULBBackendSet + BackendSet []ULBBackendSet + + // 监听器类型,枚举值为: RequestProxy -> 请求代理;PacketsTransmit -> 报文转发 + ListenType string + + // 内容转发信息列表,具体结构见下方 ULBPolicySet + PolicySet []ULBPolicySet + + // 健康检查的类型,Port:端口,Path:路径 + MonitorType string + + // MonitorType 为 Path 时指定健康检查发送请求时HTTP HEADER 里的域名 + Domain string + + // MonitorType 为 Path 时指定健康检查发送请求时的路径,默认为 / + Path string +} diff --git a/services/ulb/update_backend_attribute.go b/services/ulb/update_backend_attribute.go new file mode 100644 index 00000000..29ffb8dc --- /dev/null +++ b/services/ulb/update_backend_attribute.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB UpdateBackendAttribute + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// UpdateBackendAttributeRequest is request schema for UpdateBackendAttribute action +type UpdateBackendAttributeRequest struct { + request.CommonBase + + // 负载均衡资源ID + ULBId *string `required:"true"` + + // 后端资源实例的ID(ULB后端ID,非资源自身ID) + BackendId *string `required:"true"` + + // 后端资源服务端口,取值范围[1-65535] + Port *int `required:"false"` + + // 后端实例状态开关 + Enabled *int `required:"false"` +} + +// UpdateBackendAttributeResponse is response schema for UpdateBackendAttribute action +type UpdateBackendAttributeResponse struct { + response.CommonBase +} + +// NewUpdateBackendAttributeRequest will create request of UpdateBackendAttribute action. +func (c *ULBClient) NewUpdateBackendAttributeRequest() *UpdateBackendAttributeRequest { + req := &UpdateBackendAttributeRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// UpdateBackendAttribute - 更新ULB后端资源实例(服务节点)属性 +func (c *ULBClient) UpdateBackendAttribute(req *UpdateBackendAttributeRequest) (*UpdateBackendAttributeResponse, error) { + var err error + var res UpdateBackendAttributeResponse + + err = c.client.InvokeAction("UpdateBackendAttribute", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/update_policy.go b/services/ulb/update_policy.go new file mode 100644 index 00000000..6b34c7b8 --- /dev/null +++ b/services/ulb/update_policy.go @@ -0,0 +1,65 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB UpdatePolicy + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// UpdatePolicyRequest is request schema for UpdatePolicy action +type UpdatePolicyRequest struct { + request.CommonBase + + // 需要添加内容转发策略的负载均衡实例ID + ULBId *string `required:"true"` + + // 需要添加内容转发策略的VServer实例ID + VServerId *string `required:"true"` + + // 转发规则的ID + PolicyId *string `required:"true"` + + // 内容转发策略应用的后端资源实例的ID,来源于 AllocateBackend 返回的 BackendId + BackendId []string `required:"true"` + + // 内容转发匹配字段 + Match *string `required:"true"` + + // 内容转发匹配字段的类型 + Type *string `required:"false"` +} + +// UpdatePolicyResponse is response schema for UpdatePolicy action +type UpdatePolicyResponse struct { + response.CommonBase + + // 转发规则的ID + PolicyId string +} + +// NewUpdatePolicyRequest will create request of UpdatePolicy action. +func (c *ULBClient) NewUpdatePolicyRequest() *UpdatePolicyRequest { + req := &UpdatePolicyRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// UpdatePolicy - 更新内容转发规则,包括转发规则后的服务节点 +func (c *ULBClient) UpdatePolicy(req *UpdatePolicyRequest) (*UpdatePolicyResponse, error) { + var err error + var res UpdatePolicyResponse + + err = c.client.InvokeAction("UpdatePolicy", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/update_ulbattribute.go b/services/ulb/update_ulbattribute.go new file mode 100644 index 00000000..1af3bbfa --- /dev/null +++ b/services/ulb/update_ulbattribute.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB UpdateULBAttribute + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// UpdateULBAttributeRequest is request schema for UpdateULBAttribute action +type UpdateULBAttributeRequest struct { + request.CommonBase + + // ULB资源ID + ULBId *string `required:"true"` + + // 名字 + Name *string `required:"false"` + + // 业务 + Tag *string `required:"false"` + + // 备注 + Remark *string `required:"false"` +} + +// UpdateULBAttributeResponse is response schema for UpdateULBAttribute action +type UpdateULBAttributeResponse struct { + response.CommonBase +} + +// NewUpdateULBAttributeRequest will create request of UpdateULBAttribute action. +func (c *ULBClient) NewUpdateULBAttributeRequest() *UpdateULBAttributeRequest { + req := &UpdateULBAttributeRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// UpdateULBAttribute - 更新ULB名字业务组备注等属性字段 +func (c *ULBClient) UpdateULBAttribute(req *UpdateULBAttributeRequest) (*UpdateULBAttributeResponse, error) { + var err error + var res UpdateULBAttributeResponse + + err = c.client.InvokeAction("UpdateULBAttribute", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/ulb/update_vserver_attribute.go b/services/ulb/update_vserver_attribute.go new file mode 100644 index 00000000..a1120bf1 --- /dev/null +++ b/services/ulb/update_vserver_attribute.go @@ -0,0 +1,77 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api ULB UpdateVServerAttribute + +package ulb + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// UpdateVServerAttributeRequest is request schema for UpdateVServerAttribute action +type UpdateVServerAttributeRequest struct { + request.CommonBase + + // 负载均衡实例ID + ULBId *string `required:"true"` + + // VServer实例ID + VServerId *string `required:"true"` + + // VServer实例名称,若无此字段则不做修改 + VServerName *string `required:"false"` + + // VServer协议类型,请求代理只支持修改为 HTTP/HTTPS,报文转发VServer只支持修改为 TCP/UDP + Protocol *string `required:"false"` + + // VServer负载均衡算法,ConsistentHash,SourcePort,ConsistentHashPort 只在报文转发中使用;Roundrobin和Source在请求代理和报文转发中使用。 + Method *string `required:"false"` + + // VServer会话保持模式,若无此字段则不做修改。枚举值:None:关闭;ServerInsert:自动生成KEY;UserDefined:用户自定义KEY。 + PersistenceType *string `required:"false"` + + // 根据PersistenceType确定: None或ServerInsert, 此字段无意义; UserDefined, 则此字段传入用户自定义会话保持String. 若无此字段则不做修改 + PersistenceInfo *string `required:"false"` + + // 请求代理的VServer下表示空闲连接的回收时间,单位:秒,取值范围:时(0,86400],默认值为60;报文转发的VServer下表示回话保持的时间,单位:秒,取值范围:[60,900],0 表示禁用连接保持 + ClientTimeout *int `required:"false"` + + // 健康检查的类型,Port:端口,Path:路径 + MonitorType *string `required:"false"` + + // MonitorType 为 Path 时指定健康检查发送请求时HTTP HEADER 里的域名 + Domain *string `required:"false"` + + // MonitorType 为 Path 时指定健康检查发送请求时的路径,默认为 / + Path *string `required:"false"` +} + +// UpdateVServerAttributeResponse is response schema for UpdateVServerAttribute action +type UpdateVServerAttributeResponse struct { + response.CommonBase +} + +// NewUpdateVServerAttributeRequest will create request of UpdateVServerAttribute action. +func (c *ULBClient) NewUpdateVServerAttributeRequest() *UpdateVServerAttributeRequest { + req := &UpdateVServerAttributeRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// UpdateVServerAttribute - 更新VServer实例属性 +func (c *ULBClient) UpdateVServerAttribute(req *UpdateVServerAttributeRequest) (*UpdateVServerAttributeResponse, error) { + var err error + var res UpdateVServerAttributeResponse + + err = c.client.InvokeAction("UpdateVServerAttribute", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/allocate_eip.go b/services/unet/allocate_eip.go new file mode 100644 index 00000000..99046759 --- /dev/null +++ b/services/unet/allocate_eip.go @@ -0,0 +1,77 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet AllocateEIP + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// AllocateEIPRequest is request schema for AllocateEIP action +type AllocateEIPRequest struct { + request.CommonBase + + // 弹性IP的线路如下: 国际: International BGP: Bgp 各地域允许的线路参数如下: cn-sh1: Bgp cn-sh2: Bgp cn-gd: Bgp cn-bj1: Bgp cn-bj2: Bgp hk: International us-ca: International th-bkk: International kr-seoul:International us-ws:International ge-fra:International sg:International tw-kh:International.其他海外线路均为 International + OperatorName *string `required:"true"` + + // 弹性IP的外网带宽, 单位为Mbps. 共享带宽模式必须指定0M带宽, 非共享带宽模式必须指定非0Mbps带宽. 各地域非共享带宽的带宽范围如下: 流量计费[1-200],带宽计费[1-800] + Bandwidth *int `required:"true"` + + // 业务组名称, 默认为 "Default" + Tag *string `required:"false"` + + // 付费方式, 枚举值为: Year, 按年付费; Month, 按月付费; Dynamic, 按需付费(需开启权限); Trial, 试用(需开启权限) 默认为按月付费 + ChargeType *string `required:"false"` + + // 购买时长, 默认: 1 + Quantity *int `required:"false"` + + // 弹性IP的计费模式. 枚举值: "Traffic", 流量计费; "Bandwidth", 带宽计费; "ShareBandwidth",共享带宽模式. 默认为 "Bandwidth". + PayMode *string `required:"false"` + + // 绑定的共享带宽Id,仅当PayMode为ShareBandwidth时有效 + ShareBandwidthId *string `required:"false"` + + // 弹性IP的名称, 默认为 "EIP" + Name *string `required:"false"` + + // 弹性IP的备注, 默认为空 + Remark *string `required:"false"` + + // 代金券ID, 默认不使用 + CouponId *string `required:"false"` +} + +// AllocateEIPResponse is response schema for AllocateEIP action +type AllocateEIPResponse struct { + response.CommonBase + + // 申请到的EIP资源详情 参见 UnetAllocateEIPSet + EIPSet []UnetAllocateEIPSet +} + +// NewAllocateEIPRequest will create request of AllocateEIP action. +func (c *UNetClient) NewAllocateEIPRequest() *AllocateEIPRequest { + req := &AllocateEIPRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// AllocateEIP - 根据提供信息, 申请弹性IP +func (c *UNetClient) AllocateEIP(req *AllocateEIPRequest) (*AllocateEIPResponse, error) { + var err error + var res AllocateEIPResponse + + err = c.client.InvokeAction("AllocateEIP", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/allocate_share_bandwidth.go b/services/unet/allocate_share_bandwidth.go new file mode 100644 index 00000000..4a188f52 --- /dev/null +++ b/services/unet/allocate_share_bandwidth.go @@ -0,0 +1,62 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet AllocateShareBandwidth + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// AllocateShareBandwidthRequest is request schema for AllocateShareBandwidth action +type AllocateShareBandwidthRequest struct { + request.CommonBase + + // 共享带宽名字 + Name *string `required:"true"` + + // 付费方式:Year 按年,Month 按月,Dynamic 按时; + ChargeType *string `required:"true"` + + // 共享带宽值 + ShareBandwidth *int `required:"true"` + + // 购买时长 + Quantity *int `required:"false"` + + // 共享带宽保底值(后付费) + ShareBandwidthGuarantee *int `required:"false"` +} + +// AllocateShareBandwidthResponse is response schema for AllocateShareBandwidth action +type AllocateShareBandwidthResponse struct { + response.CommonBase + + // 共享带宽 ID + ShareBandwidthId string +} + +// NewAllocateShareBandwidthRequest will create request of AllocateShareBandwidth action. +func (c *UNetClient) NewAllocateShareBandwidthRequest() *AllocateShareBandwidthRequest { + req := &AllocateShareBandwidthRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// AllocateShareBandwidth - 开通共享带宽 +func (c *UNetClient) AllocateShareBandwidth(req *AllocateShareBandwidthRequest) (*AllocateShareBandwidthResponse, error) { + var err error + var res AllocateShareBandwidthResponse + + err = c.client.InvokeAction("AllocateShareBandwidth", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/allocate_vip.go b/services/unet/allocate_vip.go new file mode 100644 index 00000000..643f3c2f --- /dev/null +++ b/services/unet/allocate_vip.go @@ -0,0 +1,74 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet AllocateVIP + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// AllocateVIPRequest is request schema for AllocateVIP action +type AllocateVIPRequest struct { + request.CommonBase + + // 可用区 + Zone *string `required:"false"` + + // 指定vip所属的VPC + VPCId *string `required:"true"` + + // 子网id + SubnetId *string `required:"true"` + + // 申请数量,默认: 1 + Count *int `required:"false"` + + // vip名,默认为VIP + Name *string `required:"false"` + + // 业务组名称,默认为Default + Tag *string `required:"false"` + + // 备注 + Remark *string `required:"false"` + + // 业务组 + BusinessId *string `required:"false"` +} + +// AllocateVIPResponse is response schema for AllocateVIP action +type AllocateVIPResponse struct { + response.CommonBase + + // 申请到的VIP资源相关信息 + VIPSet []VIPSet + + // 申请到的VIP地址 + DataSet []string +} + +// NewAllocateVIPRequest will create request of AllocateVIP action. +func (c *UNetClient) NewAllocateVIPRequest() *AllocateVIPRequest { + req := &AllocateVIPRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// AllocateVIP - 根据提供信息,申请内网VIP(Virtual IP),多用于高可用程序作为漂移IP。 +func (c *UNetClient) AllocateVIP(req *AllocateVIPRequest) (*AllocateVIPResponse, error) { + var err error + var res AllocateVIPResponse + + err = c.client.InvokeAction("AllocateVIP", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/associate_eipwith_share_bandwidth.go b/services/unet/associate_eipwith_share_bandwidth.go new file mode 100644 index 00000000..519c4c34 --- /dev/null +++ b/services/unet/associate_eipwith_share_bandwidth.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet AssociateEIPWithShareBandwidth + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// AssociateEIPWithShareBandwidthRequest is request schema for AssociateEIPWithShareBandwidth action +type AssociateEIPWithShareBandwidthRequest struct { + request.CommonBase + + // 要加入共享带宽的EIP的资源Id + EIPIds []string `required:"true"` + + // 共享带宽ID + ShareBandwidthId *string `required:"true"` +} + +// AssociateEIPWithShareBandwidthResponse is response schema for AssociateEIPWithShareBandwidth action +type AssociateEIPWithShareBandwidthResponse struct { + response.CommonBase +} + +// NewAssociateEIPWithShareBandwidthRequest will create request of AssociateEIPWithShareBandwidth action. +func (c *UNetClient) NewAssociateEIPWithShareBandwidthRequest() *AssociateEIPWithShareBandwidthRequest { + req := &AssociateEIPWithShareBandwidthRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// AssociateEIPWithShareBandwidth - 将EIP加入共享带宽 +func (c *UNetClient) AssociateEIPWithShareBandwidth(req *AssociateEIPWithShareBandwidthRequest) (*AssociateEIPWithShareBandwidthResponse, error) { + var err error + var res AssociateEIPWithShareBandwidthResponse + + err = c.client.InvokeAction("AssociateEIPWithShareBandwidth", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/bind_eip.go b/services/unet/bind_eip.go new file mode 100644 index 00000000..bff7ed0f --- /dev/null +++ b/services/unet/bind_eip.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet BindEIP + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// BindEIPRequest is request schema for BindEIP action +type BindEIPRequest struct { + request.CommonBase + + // 弹性IP的资源Id + EIPId *string `required:"true"` + + // 弹性IP请求绑定的资源类型, 枚举值为: uhost: 云主机; vrouter: 虚拟路由器; ulb, 负载均衡器 upm: 物理机; hadoophost: 大数据集群;fortresshost:堡垒机;udockhost:容器;udhost:私有专区主机;natgw:natgw;udb:udb;vpngw:ipsec vpn;ucdr:云灾备;dbaudit:数据库审计; + ResourceType *string `required:"true"` + + // 弹性IP请求绑定的资源ID + ResourceId *string `required:"true"` +} + +// BindEIPResponse is response schema for BindEIP action +type BindEIPResponse struct { + response.CommonBase +} + +// NewBindEIPRequest will create request of BindEIP action. +func (c *UNetClient) NewBindEIPRequest() *BindEIPRequest { + req := &BindEIPRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// BindEIP - 将尚未使用的弹性IP绑定到指定的资源 +func (c *UNetClient) BindEIP(req *BindEIPRequest) (*BindEIPResponse, error) { + var err error + var res BindEIPResponse + + err = c.client.InvokeAction("BindEIP", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/client.go b/services/unet/client.go new file mode 100644 index 00000000..f0e18a78 --- /dev/null +++ b/services/unet/client.go @@ -0,0 +1,17 @@ +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type UNetClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *UNetClient { + client := ucloud.NewClient(config, credential) + return &UNetClient{ + client: client, + } +} diff --git a/services/unet/create_bandwidth_package.go b/services/unet/create_bandwidth_package.go new file mode 100644 index 00000000..d307de39 --- /dev/null +++ b/services/unet/create_bandwidth_package.go @@ -0,0 +1,62 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet CreateBandwidthPackage + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateBandwidthPackageRequest is request schema for CreateBandwidthPackage action +type CreateBandwidthPackageRequest struct { + request.CommonBase + + // 带宽大小(单位Mbps), 取值范围[2,800] (最大值受地域限制) + Bandwidth *int `required:"true"` + + // 所绑定弹性IP的资源ID + EIPId *string `required:"true"` + + // 带宽包有效时长, 取值范围为大于0的整数, 即该带宽包在EnableTime到 EnableTime+TimeRange时间段内生效 + TimeRange *int `required:"true"` + + // 生效时间, 格式为 Unix timestamp, 默认为立即开通 + EnableTime *int `required:"false"` + + // 代金券ID + CouponId *string `required:"false"` +} + +// CreateBandwidthPackageResponse is response schema for CreateBandwidthPackage action +type CreateBandwidthPackageResponse struct { + response.CommonBase + + // 所创建带宽包的资源ID + BandwidthPackageId string +} + +// NewCreateBandwidthPackageRequest will create request of CreateBandwidthPackage action. +func (c *UNetClient) NewCreateBandwidthPackageRequest() *CreateBandwidthPackageRequest { + req := &CreateBandwidthPackageRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateBandwidthPackage - 为非共享带宽模式下, 已绑定资源实例的带宽计费弹性IP附加临时带宽包 +func (c *UNetClient) CreateBandwidthPackage(req *CreateBandwidthPackageRequest) (*CreateBandwidthPackageResponse, error) { + var err error + var res CreateBandwidthPackageResponse + + err = c.client.InvokeAction("CreateBandwidthPackage", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/create_firewall.go b/services/unet/create_firewall.go new file mode 100644 index 00000000..ede007d5 --- /dev/null +++ b/services/unet/create_firewall.go @@ -0,0 +1,59 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet CreateFirewall + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateFirewallRequest is request schema for CreateFirewall action +type CreateFirewallRequest struct { + request.CommonBase + + // 防火墙规则,例如:TCP|22|192.168.1.1/22|DROP|LOW,第一个参数代表协议:第二个参数代表端口号,第三个参数为ip,第四个参数为ACCEPT(接受)和DROP(拒绝),第五个参数优先级:HIGH(高),MEDIUM(中),LOW(低) + Rule []string `required:"true"` + + // 防火墙名称, 默认为Firewall + Name *string `required:"false"` + + // 防火墙业务组,默认为Default + Tag *string `required:"false"` + + // 防火墙描述,默认为空 + Remark *string `required:"false"` +} + +// CreateFirewallResponse is response schema for CreateFirewall action +type CreateFirewallResponse struct { + response.CommonBase + + // 防火墙 ID + FWId string +} + +// NewCreateFirewallRequest will create request of CreateFirewall action. +func (c *UNetClient) NewCreateFirewallRequest() *CreateFirewallRequest { + req := &CreateFirewallRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateFirewall - 创建防火墙 +func (c *UNetClient) CreateFirewall(req *CreateFirewallRequest) (*CreateFirewallResponse, error) { + var err error + var res CreateFirewallResponse + + err = c.client.InvokeAction("CreateFirewall", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/delete_bandwidth_package.go b/services/unet/delete_bandwidth_package.go new file mode 100644 index 00000000..e1477a2b --- /dev/null +++ b/services/unet/delete_bandwidth_package.go @@ -0,0 +1,47 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DeleteBandwidthPackage + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeleteBandwidthPackageRequest is request schema for DeleteBandwidthPackage action +type DeleteBandwidthPackageRequest struct { + request.CommonBase + + // 带宽包资源ID + BandwidthPackageId *string `required:"true"` +} + +// DeleteBandwidthPackageResponse is response schema for DeleteBandwidthPackage action +type DeleteBandwidthPackageResponse struct { + response.CommonBase +} + +// NewDeleteBandwidthPackageRequest will create request of DeleteBandwidthPackage action. +func (c *UNetClient) NewDeleteBandwidthPackageRequest() *DeleteBandwidthPackageRequest { + req := &DeleteBandwidthPackageRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DeleteBandwidthPackage - 删除弹性IP上已附加带宽包 +func (c *UNetClient) DeleteBandwidthPackage(req *DeleteBandwidthPackageRequest) (*DeleteBandwidthPackageResponse, error) { + var err error + var res DeleteBandwidthPackageResponse + + err = c.client.InvokeAction("DeleteBandwidthPackage", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/delete_firewall.go b/services/unet/delete_firewall.go new file mode 100644 index 00000000..bf9e9f44 --- /dev/null +++ b/services/unet/delete_firewall.go @@ -0,0 +1,47 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DeleteFirewall + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeleteFirewallRequest is request schema for DeleteFirewall action +type DeleteFirewallRequest struct { + request.CommonBase + + // 防火墙资源ID + FWId *string `required:"true"` +} + +// DeleteFirewallResponse is response schema for DeleteFirewall action +type DeleteFirewallResponse struct { + response.CommonBase +} + +// NewDeleteFirewallRequest will create request of DeleteFirewall action. +func (c *UNetClient) NewDeleteFirewallRequest() *DeleteFirewallRequest { + req := &DeleteFirewallRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DeleteFirewall - 删除防火墙 +func (c *UNetClient) DeleteFirewall(req *DeleteFirewallRequest) (*DeleteFirewallResponse, error) { + var err error + var res DeleteFirewallResponse + + err = c.client.InvokeAction("DeleteFirewall", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/describe_bandwidth_package.go b/services/unet/describe_bandwidth_package.go new file mode 100644 index 00000000..20d9ceec --- /dev/null +++ b/services/unet/describe_bandwidth_package.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DescribeBandwidthPackage + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeBandwidthPackageRequest is request schema for DescribeBandwidthPackage action +type DescribeBandwidthPackageRequest struct { + request.CommonBase + + // 返回数据分页值, 取值范围为 [0,10000000] 之间的整数, 默认为20 + Limit *int `required:"false"` + + // 返回数据偏移量, 默认为0 + Offset *int `required:"false"` +} + +// DescribeBandwidthPackageResponse is response schema for DescribeBandwidthPackage action +type DescribeBandwidthPackageResponse struct { + response.CommonBase + + // 满足条件的带宽包总数 + TotalCount int + + // 带宽包详细信息, 参见 UnetBandwidthPackageSet + DataSets []UnetBandwidthPackageSet +} + +// NewDescribeBandwidthPackageRequest will create request of DescribeBandwidthPackage action. +func (c *UNetClient) NewDescribeBandwidthPackageRequest() *DescribeBandwidthPackageRequest { + req := &DescribeBandwidthPackageRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeBandwidthPackage - 获取某地域下的带宽包信息 +func (c *UNetClient) DescribeBandwidthPackage(req *DescribeBandwidthPackageRequest) (*DescribeBandwidthPackageResponse, error) { + var err error + var res DescribeBandwidthPackageResponse + + err = c.client.InvokeAction("DescribeBandwidthPackage", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/describe_bandwidth_usage.go b/services/unet/describe_bandwidth_usage.go new file mode 100644 index 00000000..68b00174 --- /dev/null +++ b/services/unet/describe_bandwidth_usage.go @@ -0,0 +1,59 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DescribeBandwidthUsage + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeBandwidthUsageRequest is request schema for DescribeBandwidthUsage action +type DescribeBandwidthUsageRequest struct { + request.CommonBase + + // 返回数据分页值, 取值范围为 [0,10000000] 之间的整数, 默认为20 + Limit *int `required:"false"` + + // 返回数据偏移量, 默认为0 + OffSet *int `required:"false"` + + // 弹性IP的资源Id. 如果为空, 则返回当前 Region中符合条件的所有EIP的带宽用量, n为自然数 + EIPIds []string `required:"false"` +} + +// DescribeBandwidthUsageResponse is response schema for DescribeBandwidthUsage action +type DescribeBandwidthUsageResponse struct { + response.CommonBase + + // EIPSet中的元素个数 + TotalCount int + + // 单个弹性IP的带宽用量详细信息, 详见 UnetBandwidthUsageEIPSet, 如没有弹性IP资源则没有该返回值。 + EIPSet []UnetBandwidthUsageEIPSet +} + +// NewDescribeBandwidthUsageRequest will create request of DescribeBandwidthUsage action. +func (c *UNetClient) NewDescribeBandwidthUsageRequest() *DescribeBandwidthUsageRequest { + req := &DescribeBandwidthUsageRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeBandwidthUsage - 获取带宽用量信息 +func (c *UNetClient) DescribeBandwidthUsage(req *DescribeBandwidthUsageRequest) (*DescribeBandwidthUsageResponse, error) { + var err error + var res DescribeBandwidthUsageResponse + + err = c.client.InvokeAction("DescribeBandwidthUsage", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/describe_eip.go b/services/unet/describe_eip.go new file mode 100644 index 00000000..d5149704 --- /dev/null +++ b/services/unet/describe_eip.go @@ -0,0 +1,62 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DescribeEIP + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeEIPRequest is request schema for DescribeEIP action +type DescribeEIPRequest struct { + request.CommonBase + + // 弹性IP的资源ID如果为空, 则返回当前 Region中符合条件的的所有EIP + EIPIds []string `required:"false"` + + // 数据偏移量, 默认为0 + Offset *int `required:"false"` + + // 数据分页值, 默认为20 + Limit *int `required:"false"` +} + +// DescribeEIPResponse is response schema for DescribeEIP action +type DescribeEIPResponse struct { + response.CommonBase + + // 满足条件的弹性IP总数 + TotalCount int + + // 满足条件的弹性IP带宽总和, 单位Mbps + TotalBandwidth int + + // 弹性IP列表, 每项参数详见 UnetEIPSet + EIPSet []UnetEIPSet +} + +// NewDescribeEIPRequest will create request of DescribeEIP action. +func (c *UNetClient) NewDescribeEIPRequest() *DescribeEIPRequest { + req := &DescribeEIPRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeEIP - 获取弹性IP信息 +func (c *UNetClient) DescribeEIP(req *DescribeEIPRequest) (*DescribeEIPResponse, error) { + var err error + var res DescribeEIPResponse + + err = c.client.InvokeAction("DescribeEIP", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/describe_firewall.go b/services/unet/describe_firewall.go new file mode 100644 index 00000000..409e7938 --- /dev/null +++ b/services/unet/describe_firewall.go @@ -0,0 +1,62 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DescribeFirewall + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeFirewallRequest is request schema for DescribeFirewall action +type DescribeFirewallRequest struct { + request.CommonBase + + // 防火墙ID,默认为返回所有防火墙 + FWId *string `required:"false"` + + // 绑定防火墙组的资源类型,如uhost + ResourceType *string `required:"false"` + + // 绑定防火墙组的资源ID + ResourceId *string `required:"false"` + + // 返回数据长度,默认为20,最大10000000 + Limit *string `required:"false"` + + // 列表起始位置偏移量,默认为0 + Offset *string `required:"false"` +} + +// DescribeFirewallResponse is response schema for DescribeFirewall action +type DescribeFirewallResponse struct { + response.CommonBase + + // 获取的防火墙组详细信息 参见 FirewallDataSet + DataSet []FirewallDataSet +} + +// NewDescribeFirewallRequest will create request of DescribeFirewall action. +func (c *UNetClient) NewDescribeFirewallRequest() *DescribeFirewallRequest { + req := &DescribeFirewallRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeFirewall - 获取防火墙组信息 +func (c *UNetClient) DescribeFirewall(req *DescribeFirewallRequest) (*DescribeFirewallResponse, error) { + var err error + var res DescribeFirewallResponse + + err = c.client.InvokeAction("DescribeFirewall", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/describe_firewall_resource.go b/services/unet/describe_firewall_resource.go new file mode 100644 index 00000000..da4c85bd --- /dev/null +++ b/services/unet/describe_firewall_resource.go @@ -0,0 +1,59 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DescribeFirewallResource + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeFirewallResourceRequest is request schema for DescribeFirewallResource action +type DescribeFirewallResourceRequest struct { + request.CommonBase + + // 防火墙ID + FWId *string `required:"true"` + + // 返回数据长度,默认为20,最大10000000 + Limit *string `required:"false"` + + // 列表起始位置偏移量,默认为0 + Offset *string `required:"false"` +} + +// DescribeFirewallResourceResponse is response schema for DescribeFirewallResource action +type DescribeFirewallResourceResponse struct { + response.CommonBase + + // 资源列表,见 ResourceSet + ResourceSet []ResourceSet + + // 防火墙已绑定资源的总数 + TotalCount int +} + +// NewDescribeFirewallResourceRequest will create request of DescribeFirewallResource action. +func (c *UNetClient) NewDescribeFirewallResourceRequest() *DescribeFirewallResourceRequest { + req := &DescribeFirewallResourceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeFirewallResource - 获取防火墙组所绑定资源的外网IP +func (c *UNetClient) DescribeFirewallResource(req *DescribeFirewallResourceRequest) (*DescribeFirewallResourceResponse, error) { + var err error + var res DescribeFirewallResourceResponse + + err = c.client.InvokeAction("DescribeFirewallResource", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/describe_share_bandwidth.go b/services/unet/describe_share_bandwidth.go new file mode 100644 index 00000000..e953e599 --- /dev/null +++ b/services/unet/describe_share_bandwidth.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DescribeShareBandwidth + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeShareBandwidthRequest is request schema for DescribeShareBandwidth action +type DescribeShareBandwidthRequest struct { + request.CommonBase + + // 需要返回的共享带宽Id + ShareBandwidthIds []string `required:"false"` +} + +// DescribeShareBandwidthResponse is response schema for DescribeShareBandwidth action +type DescribeShareBandwidthResponse struct { + response.CommonBase + + // 共享带宽信息组 参见 UnetShareBandwidthSet + DataSet []UnetShareBandwidthSet + + // 符合条件的共享带宽总数,大于等于返回DataSet长度 + TotalCount int +} + +// NewDescribeShareBandwidthRequest will create request of DescribeShareBandwidth action. +func (c *UNetClient) NewDescribeShareBandwidthRequest() *DescribeShareBandwidthRequest { + req := &DescribeShareBandwidthRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeShareBandwidth - 获取共享带宽信息 +func (c *UNetClient) DescribeShareBandwidth(req *DescribeShareBandwidthRequest) (*DescribeShareBandwidthResponse, error) { + var err error + var res DescribeShareBandwidthResponse + + err = c.client.InvokeAction("DescribeShareBandwidth", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/describe_vip.go b/services/unet/describe_vip.go new file mode 100644 index 00000000..3213fb43 --- /dev/null +++ b/services/unet/describe_vip.go @@ -0,0 +1,68 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DescribeVIP + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeVIPRequest is request schema for DescribeVIP action +type DescribeVIPRequest struct { + request.CommonBase + + // 可用区。参见 [可用区列表](../summary/regionlist.html) + Zone *string `required:"false"` + + // vpc的id,指定SubnetId时必填 + VPCId *string `required:"false"` + + // 子网id,不指定则获取VPCId下的所有vip + SubnetId *string `required:"false"` + + // 业务组名称, 默认为 Default + Tag *string `required:"false"` + + // 业务组 + BusinessId *string `required:"false"` +} + +// DescribeVIPResponse is response schema for DescribeVIP action +type DescribeVIPResponse struct { + response.CommonBase + + // 内网VIP详情 + VIPSet []VIPDetailSet + + // 内网VIP地址列表 + DataSet []string + + // vip数量 + TotalCount int +} + +// NewDescribeVIPRequest will create request of DescribeVIP action. +func (c *UNetClient) NewDescribeVIPRequest() *DescribeVIPRequest { + req := &DescribeVIPRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeVIP - 获取内网VIP详细信息 +func (c *UNetClient) DescribeVIP(req *DescribeVIPRequest) (*DescribeVIPResponse, error) { + var err error + var res DescribeVIPResponse + + err = c.client.InvokeAction("DescribeVIP", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/disassociate_eipwith_share_bandwidth.go b/services/unet/disassociate_eipwith_share_bandwidth.go new file mode 100644 index 00000000..d30c255d --- /dev/null +++ b/services/unet/disassociate_eipwith_share_bandwidth.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet DisassociateEIPWithShareBandwidth + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DisassociateEIPWithShareBandwidthRequest is request schema for DisassociateEIPWithShareBandwidth action +type DisassociateEIPWithShareBandwidthRequest struct { + request.CommonBase + + // 共享带宽ID + ShareBandwidthId *string `required:"true"` + + // 移出共享带宽后,EIP的外网带宽, 单位为Mbps. 各地域带宽范围如下: 流量计费[1-200],带宽计费[1-800] + Bandwidth *int `required:"true"` + + // EIP的资源Id;默认移出该共享带宽下所有的EIP + EIPIds []string `required:"false"` + + // 移出共享带宽后,EIP的计费模式. 枚举值: "Traffic", 流量计费; "Bandwidth", 带宽计费; 默认为 "Bandwidth". + PayMode *string `required:"false"` +} + +// DisassociateEIPWithShareBandwidthResponse is response schema for DisassociateEIPWithShareBandwidth action +type DisassociateEIPWithShareBandwidthResponse struct { + response.CommonBase +} + +// NewDisassociateEIPWithShareBandwidthRequest will create request of DisassociateEIPWithShareBandwidth action. +func (c *UNetClient) NewDisassociateEIPWithShareBandwidthRequest() *DisassociateEIPWithShareBandwidthRequest { + req := &DisassociateEIPWithShareBandwidthRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DisassociateEIPWithShareBandwidth - 将EIP移出共享带宽 +func (c *UNetClient) DisassociateEIPWithShareBandwidth(req *DisassociateEIPWithShareBandwidthRequest) (*DisassociateEIPWithShareBandwidthResponse, error) { + var err error + var res DisassociateEIPWithShareBandwidthResponse + + err = c.client.InvokeAction("DisassociateEIPWithShareBandwidth", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/doc.go b/services/unet/doc.go new file mode 100644 index 00000000..f9caeeca --- /dev/null +++ b/services/unet/doc.go @@ -0,0 +1,11 @@ +/* + Package unet include resources of ucloud unet product + + See also + + - API: https://docs.ucloud.cn/api/unet-api/index + - Product: https://www.ucloud.cn/site/product/unet.html + + for detail. +*/ +package unet diff --git a/services/unet/get_eippay_mode.go b/services/unet/get_eippay_mode.go new file mode 100644 index 00000000..e1054bf1 --- /dev/null +++ b/services/unet/get_eippay_mode.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet GetEIPPayMode + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetEIPPayModeRequest is request schema for GetEIPPayMode action +type GetEIPPayModeRequest struct { + request.CommonBase + + // 弹性IP的资源Id + EIPId []string `required:"true"` +} + +// GetEIPPayModeResponse is response schema for GetEIPPayMode action +type GetEIPPayModeResponse struct { + response.CommonBase + + // EIP的计费模式, 参见 EIPPayModeSet + EIPPayMode []EIPPayModeSet +} + +// NewGetEIPPayModeRequest will create request of GetEIPPayMode action. +func (c *UNetClient) NewGetEIPPayModeRequest() *GetEIPPayModeRequest { + req := &GetEIPPayModeRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// GetEIPPayMode - 获取弹性IP计费模式 +func (c *UNetClient) GetEIPPayMode(req *GetEIPPayModeRequest) (*GetEIPPayModeResponse, error) { + var err error + var res GetEIPPayModeResponse + + err = c.client.InvokeAction("GetEIPPayMode", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/get_eipprice.go b/services/unet/get_eipprice.go new file mode 100644 index 00000000..9dc1bb4a --- /dev/null +++ b/services/unet/get_eipprice.go @@ -0,0 +1,59 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet GetEIPPrice + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetEIPPriceRequest is request schema for GetEIPPrice action +type GetEIPPriceRequest struct { + request.CommonBase + + // 弹性IP的线路如下: 国际: International BGP: Bgp 各地域允许的线路参数如下: cn-sh1: Bgp cn-sh2: Bgp cn-gd: Bgp cn-bj1: Bgp cn-bj2: Bgp hk: International us-ca: International th-bkk: International kr-seoul:International us-ws:International ge-fra:International sg:International tw-kh:International.其他海外线路均为 International + OperatorName *string `required:"true"` + + // 弹性IP的外网带宽, 单位为Mbps, 范围 [0-800] + Bandwidth *int `required:"true"` + + // 付费方式, 枚举值为: Year, 按年付费; Month, 按月付费; Dynamic, 按需付费(需开启权限); 默认为获取三种价格 + ChargeType *string `required:"false"` + + // 弹性IP计费方式r. 枚举值为: Traffic, 流量计费; Bandwidth, 带宽计费; "ShareBandwidth",共享带宽模式. 默认为Bandwidth + PayMode *string `required:"false"` +} + +// GetEIPPriceResponse is response schema for GetEIPPrice action +type GetEIPPriceResponse struct { + response.CommonBase + + // 弹性IP价格详情 详情见 EIPPriceDetailSet + PriceSet []EIPPriceDetailSet +} + +// NewGetEIPPriceRequest will create request of GetEIPPrice action. +func (c *UNetClient) NewGetEIPPriceRequest() *GetEIPPriceRequest { + req := &GetEIPPriceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// GetEIPPrice - 获取弹性IP价格 +func (c *UNetClient) GetEIPPrice(req *GetEIPPriceRequest) (*GetEIPPriceResponse, error) { + var err error + var res GetEIPPriceResponse + + err = c.client.InvokeAction("GetEIPPrice", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/get_eipupgrade_price.go b/services/unet/get_eipupgrade_price.go new file mode 100644 index 00000000..97e9ff39 --- /dev/null +++ b/services/unet/get_eipupgrade_price.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet GetEIPUpgradePrice + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GetEIPUpgradePriceRequest is request schema for GetEIPUpgradePrice action +type GetEIPUpgradePriceRequest struct { + request.CommonBase + + // 弹性IP的资源ID + EIPId *string `required:"true"` + + // 弹性IP的外网带宽, 单位为Mbps, 范围 [1-800] + Bandwidth *int `required:"true"` +} + +// GetEIPUpgradePriceResponse is response schema for GetEIPUpgradePrice action +type GetEIPUpgradePriceResponse struct { + response.CommonBase + + // 调整带宽后的EIP价格, 单位为"元", 如需退费此处为负值 + Price float64 +} + +// NewGetEIPUpgradePriceRequest will create request of GetEIPUpgradePrice action. +func (c *UNetClient) NewGetEIPUpgradePriceRequest() *GetEIPUpgradePriceRequest { + req := &GetEIPUpgradePriceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// GetEIPUpgradePrice - 获取弹性IP带宽改动价格 +func (c *UNetClient) GetEIPUpgradePrice(req *GetEIPUpgradePriceRequest) (*GetEIPUpgradePriceResponse, error) { + var err error + var res GetEIPUpgradePriceResponse + + err = c.client.InvokeAction("GetEIPUpgradePrice", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/grant_firewall.go b/services/unet/grant_firewall.go new file mode 100644 index 00000000..9dab5ca8 --- /dev/null +++ b/services/unet/grant_firewall.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet GrantFirewall + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// GrantFirewallRequest is request schema for GrantFirewall action +type GrantFirewallRequest struct { + request.CommonBase + + // 防火墙资源ID + FWId *string `required:"true"` + + // 所应用资源类型,如UHost + ResourceType *string `required:"true"` + + // 所应用资源ID + ResourceId *string `required:"true"` +} + +// GrantFirewallResponse is response schema for GrantFirewall action +type GrantFirewallResponse struct { + response.CommonBase +} + +// NewGrantFirewallRequest will create request of GrantFirewall action. +func (c *UNetClient) NewGrantFirewallRequest() *GrantFirewallRequest { + req := &GrantFirewallRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// GrantFirewall - 将防火墙应用到资源上 +func (c *UNetClient) GrantFirewall(req *GrantFirewallRequest) (*GrantFirewallResponse, error) { + var err error + var res GrantFirewallResponse + + err = c.client.InvokeAction("GrantFirewall", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/modify_eipbandwidth.go b/services/unet/modify_eipbandwidth.go new file mode 100644 index 00000000..39d47b09 --- /dev/null +++ b/services/unet/modify_eipbandwidth.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet ModifyEIPBandwidth + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ModifyEIPBandwidthRequest is request schema for ModifyEIPBandwidth action +type ModifyEIPBandwidthRequest struct { + request.CommonBase + + // 弹性IP的资源ID + EIPId *string `required:"true"` + + // 弹性IP的外网带宽, 单位为Mbps. 各地域的带宽值范围如下:流量计费[1-200],带宽计费[1-800] + Bandwidth *int `required:"true"` +} + +// ModifyEIPBandwidthResponse is response schema for ModifyEIPBandwidth action +type ModifyEIPBandwidthResponse struct { + response.CommonBase +} + +// NewModifyEIPBandwidthRequest will create request of ModifyEIPBandwidth action. +func (c *UNetClient) NewModifyEIPBandwidthRequest() *ModifyEIPBandwidthRequest { + req := &ModifyEIPBandwidthRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ModifyEIPBandwidth - 调整弹性IP的外网带宽 +func (c *UNetClient) ModifyEIPBandwidth(req *ModifyEIPBandwidthRequest) (*ModifyEIPBandwidthResponse, error) { + var err error + var res ModifyEIPBandwidthResponse + + err = c.client.InvokeAction("ModifyEIPBandwidth", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/modify_eipweight.go b/services/unet/modify_eipweight.go new file mode 100644 index 00000000..5a02f105 --- /dev/null +++ b/services/unet/modify_eipweight.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet ModifyEIPWeight + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ModifyEIPWeightRequest is request schema for ModifyEIPWeight action +type ModifyEIPWeightRequest struct { + request.CommonBase + + // 弹性IP的资源ID + EIPId *string `required:"true"` + + // 外网出口权重, 范围[0-100] 取值为0时, 该弹性IP不会被使用. 取值为100时, 同主机下只会使用这个弹性IP,其他弹性IP不会被使用 请勿将多个绑定在同一资源的弹性IP设置为相同权重 + Weight *int `required:"true"` +} + +// ModifyEIPWeightResponse is response schema for ModifyEIPWeight action +type ModifyEIPWeightResponse struct { + response.CommonBase +} + +// NewModifyEIPWeightRequest will create request of ModifyEIPWeight action. +func (c *UNetClient) NewModifyEIPWeightRequest() *ModifyEIPWeightRequest { + req := &ModifyEIPWeightRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ModifyEIPWeight - 修改弹性IP的外网出口权重 +func (c *UNetClient) ModifyEIPWeight(req *ModifyEIPWeightRequest) (*ModifyEIPWeightResponse, error) { + var err error + var res ModifyEIPWeightResponse + + err = c.client.InvokeAction("ModifyEIPWeight", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/release_eip.go b/services/unet/release_eip.go new file mode 100644 index 00000000..04a8e671 --- /dev/null +++ b/services/unet/release_eip.go @@ -0,0 +1,47 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet ReleaseEIP + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ReleaseEIPRequest is request schema for ReleaseEIP action +type ReleaseEIPRequest struct { + request.CommonBase + + // 弹性IP的资源ID + EIPId *string `required:"true"` +} + +// ReleaseEIPResponse is response schema for ReleaseEIP action +type ReleaseEIPResponse struct { + response.CommonBase +} + +// NewReleaseEIPRequest will create request of ReleaseEIP action. +func (c *UNetClient) NewReleaseEIPRequest() *ReleaseEIPRequest { + req := &ReleaseEIPRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ReleaseEIP - 释放弹性IP资源, 所释放弹性IP必须为非绑定状态. +func (c *UNetClient) ReleaseEIP(req *ReleaseEIPRequest) (*ReleaseEIPResponse, error) { + var err error + var res ReleaseEIPResponse + + err = c.client.InvokeAction("ReleaseEIP", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/release_share_bandwidth.go b/services/unet/release_share_bandwidth.go new file mode 100644 index 00000000..5f2f03bc --- /dev/null +++ b/services/unet/release_share_bandwidth.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet ReleaseShareBandwidth + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ReleaseShareBandwidthRequest is request schema for ReleaseShareBandwidth action +type ReleaseShareBandwidthRequest struct { + request.CommonBase + + // 共享带宽ID + ShareBandwidthId *string `required:"true"` + + // 关闭共享带宽后,各EIP恢复为的带宽值 + EIPBandwidth *int `required:"true"` + + // Bandwidth 带宽计费, Traffic 转流量计费 + PayMode *string `required:"false"` +} + +// ReleaseShareBandwidthResponse is response schema for ReleaseShareBandwidth action +type ReleaseShareBandwidthResponse struct { + response.CommonBase +} + +// NewReleaseShareBandwidthRequest will create request of ReleaseShareBandwidth action. +func (c *UNetClient) NewReleaseShareBandwidthRequest() *ReleaseShareBandwidthRequest { + req := &ReleaseShareBandwidthRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ReleaseShareBandwidth - 关闭共享带宽 +func (c *UNetClient) ReleaseShareBandwidth(req *ReleaseShareBandwidthRequest) (*ReleaseShareBandwidthResponse, error) { + var err error + var res ReleaseShareBandwidthResponse + + err = c.client.InvokeAction("ReleaseShareBandwidth", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/release_vip.go b/services/unet/release_vip.go new file mode 100644 index 00000000..6cc0aced --- /dev/null +++ b/services/unet/release_vip.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet ReleaseVIP + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ReleaseVIPRequest is request schema for ReleaseVIP action +type ReleaseVIPRequest struct { + request.CommonBase + + // 可用区 + Zone *string `required:"false"` + + // 内网VIP的id + VIPId *string `required:"true"` +} + +// ReleaseVIPResponse is response schema for ReleaseVIP action +type ReleaseVIPResponse struct { + response.CommonBase +} + +// NewReleaseVIPRequest will create request of ReleaseVIP action. +func (c *UNetClient) NewReleaseVIPRequest() *ReleaseVIPRequest { + req := &ReleaseVIPRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ReleaseVIP - 释放VIP资源 +func (c *UNetClient) ReleaseVIP(req *ReleaseVIPRequest) (*ReleaseVIPResponse, error) { + var err error + var res ReleaseVIPResponse + + err = c.client.InvokeAction("ReleaseVIP", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/resize_share_bandwidth.go b/services/unet/resize_share_bandwidth.go new file mode 100644 index 00000000..606483c9 --- /dev/null +++ b/services/unet/resize_share_bandwidth.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet ResizeShareBandwidth + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ResizeShareBandwidthRequest is request schema for ResizeShareBandwidth action +type ResizeShareBandwidthRequest struct { + request.CommonBase + + // 带宽值,单位为Mb,范围 [20-5000] (最大值受地域限制) + ShareBandwidth *int `required:"true"` + + // 共享带宽的Id + ShareBandwidthId *string `required:"true"` +} + +// ResizeShareBandwidthResponse is response schema for ResizeShareBandwidth action +type ResizeShareBandwidthResponse struct { + response.CommonBase +} + +// NewResizeShareBandwidthRequest will create request of ResizeShareBandwidth action. +func (c *UNetClient) NewResizeShareBandwidthRequest() *ResizeShareBandwidthRequest { + req := &ResizeShareBandwidthRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// ResizeShareBandwidth - 调整共享带宽的带宽值 +func (c *UNetClient) ResizeShareBandwidth(req *ResizeShareBandwidthRequest) (*ResizeShareBandwidthResponse, error) { + var err error + var res ResizeShareBandwidthResponse + + err = c.client.InvokeAction("ResizeShareBandwidth", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/set_eippay_mode.go b/services/unet/set_eippay_mode.go new file mode 100644 index 00000000..72e8c454 --- /dev/null +++ b/services/unet/set_eippay_mode.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet SetEIPPayMode + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// SetEIPPayModeRequest is request schema for SetEIPPayMode action +type SetEIPPayModeRequest struct { + request.CommonBase + + // 弹性IP的资源Id + EIPId *string `required:"true"` + + // 计费模式. 枚举值:"Traffic", 流量计费模式; "Bandwidth", 带宽计费模式 + PayMode *string `required:"true"` + + // 调整的目标带宽值, 单位Mbps. 各地域的带宽值范围如下: 流量计费[1-200],其余情况[1-800] + Bandwidth *int `required:"true"` +} + +// SetEIPPayModeResponse is response schema for SetEIPPayMode action +type SetEIPPayModeResponse struct { + response.CommonBase +} + +// NewSetEIPPayModeRequest will create request of SetEIPPayMode action. +func (c *UNetClient) NewSetEIPPayModeRequest() *SetEIPPayModeRequest { + req := &SetEIPPayModeRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// SetEIPPayMode - 设置弹性IP计费模式, 切换时会涉及付费/退费. +func (c *UNetClient) SetEIPPayMode(req *SetEIPPayModeRequest) (*SetEIPPayModeResponse, error) { + var err error + var res SetEIPPayModeResponse + + err = c.client.InvokeAction("SetEIPPayMode", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/types_eipaddr_set.go b/services/unet/types_eipaddr_set.go new file mode 100644 index 00000000..8d511701 --- /dev/null +++ b/services/unet/types_eipaddr_set.go @@ -0,0 +1,16 @@ +package unet + +/* + EIPAddrSet - DescribeShareBandwidth + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type EIPAddrSet struct { + + // 运营商信息, 枚举值为: Telecom 电信; Unicom: 联通; Duplet: 双线; Bgp: BGP; International: 国际. + OperatorName string + + // 弹性IP地址 + IP string +} diff --git a/services/unet/types_eippay_mode_set.go b/services/unet/types_eippay_mode_set.go new file mode 100644 index 00000000..37f03b9a --- /dev/null +++ b/services/unet/types_eippay_mode_set.go @@ -0,0 +1,16 @@ +package unet + +/* + EIPPayModeSet - GetEIPPayModeEIP + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type EIPPayModeSet struct { + + // EIP的资源ID + EIPId string + + // EIP的计费模式. 枚举值为:Bandwidth, 带宽计费;Traffic, 流量计费; "ShareBandwidth",共享带宽模式 + EIPPayMode string +} diff --git a/services/unet/types_eipprice_detail_set.go b/services/unet/types_eipprice_detail_set.go new file mode 100644 index 00000000..cc5f8649 --- /dev/null +++ b/services/unet/types_eipprice_detail_set.go @@ -0,0 +1,19 @@ +package unet + +/* + EIPPriceDetailSet - GetEIPPrice + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type EIPPriceDetailSet struct { + + // 弹性IP付费方式 + ChargeType string + + // 弹性IP价格, 单位"元" + Price float64 + + // 资源有效期, 以Unix Timestamp表示 + PurchaseValue int +} diff --git a/services/unet/types_eipset_data.go b/services/unet/types_eipset_data.go new file mode 100644 index 00000000..9235d53c --- /dev/null +++ b/services/unet/types_eipset_data.go @@ -0,0 +1,19 @@ +package unet + +/* + EIPSetData - describeShareBandwidth + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type EIPSetData struct { + + // EIP带宽值 + Badnwidth int + + // EIP的IP信息,详情见EIPAddrSet + EIPAddr []EIPAddrSet + + // EIP资源Id + EIPId string +} diff --git a/services/unet/types_firewall_data_set.go b/services/unet/types_firewall_data_set.go new file mode 100644 index 00000000..6157ff5d --- /dev/null +++ b/services/unet/types_firewall_data_set.go @@ -0,0 +1,37 @@ +package unet + +/* + FirewallDataSet - DescribeFirewall + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type FirewallDataSet struct { + + // 防火墙名称 + Name string + + // 防火墙业务组 + Tag string + + // 防火墙备注 + Remark string + + // 防火墙绑定资源数量 + ResourceCount int + + // 防火墙组创建时间,格式为Unix Timestamp + CreateTime int + + // 防火墙组类型,枚举值为: "user defined", 用户自定义防火墙; "recommend web", 默认Web防火墙; "recommend non web", 默认非Web防火墙 + Type string + + // 防火墙组中的规则列表,参见 FirewallRuleSet + Rule []FirewallRuleSet + + // 防火墙 ID + FWId string + + // 安全组 ID(即将弃用) + GroupId string +} diff --git a/services/unet/types_firewall_rule_set.go b/services/unet/types_firewall_rule_set.go new file mode 100644 index 00000000..fa1e9e2f --- /dev/null +++ b/services/unet/types_firewall_rule_set.go @@ -0,0 +1,25 @@ +package unet + +/* + FirewallRuleSet - DescribeFirewall + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type FirewallRuleSet struct { + + // 源地址 + SrcIP string + + // 优先级 + Priority string + + // 协议类型 + ProtocolType string + + // 目标端口 + DstPort string + + // 防火墙动作 + RuleAction string +} diff --git a/services/unet/types_resource_set.go b/services/unet/types_resource_set.go new file mode 100644 index 00000000..6a5e16f2 --- /dev/null +++ b/services/unet/types_resource_set.go @@ -0,0 +1,34 @@ +package unet + +/* + ResourceSet - 资源信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ResourceSet struct { + + // 名称 + Name string + + // 内网IP + PrivateIP string + + // 备注 + Remark string + + // 绑定该防火墙的资源id + ResourceID string + + // 绑定资源的资源类型 + ResourceType string + + // 状态 + Status string + + // 业务组 + Tag string + + // 可用区 + Zone int +} diff --git a/services/unet/types_share_bandwidth_set.go b/services/unet/types_share_bandwidth_set.go new file mode 100644 index 00000000..88815476 --- /dev/null +++ b/services/unet/types_share_bandwidth_set.go @@ -0,0 +1,19 @@ +package unet + +/* + ShareBandwidthSet - DescribeEIP + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ShareBandwidthSet struct { + + // 共享带宽带宽值 + ShareBandwidth int + + // 共享带宽的资源名称 + ShareBandwidthName string + + // 共享带宽ID + ShareBandwidthId string +} diff --git a/services/unet/types_unet_allocate_eipset.go b/services/unet/types_unet_allocate_eipset.go new file mode 100644 index 00000000..ef720e98 --- /dev/null +++ b/services/unet/types_unet_allocate_eipset.go @@ -0,0 +1,16 @@ +package unet + +/* + UnetAllocateEIPSet - AllocateEIP + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UnetAllocateEIPSet struct { + + // 申请到的EIP资源ID + EIPId string + + // 申请到的IPv4地址. + EIPAddr []UnetEIPAddrSet +} diff --git a/services/unet/types_unet_bandwidth_package_set.go b/services/unet/types_unet_bandwidth_package_set.go new file mode 100644 index 00000000..c742ca6a --- /dev/null +++ b/services/unet/types_unet_bandwidth_package_set.go @@ -0,0 +1,31 @@ +package unet + +/* + UnetBandwidthPackageSet - DescribeBandwidthPackage + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UnetBandwidthPackageSet struct { + + // 带宽包的资源ID + BandwidthPackageId string + + // 生效时间, 格式为 Unix Timestamp + EnableTime int + + // 失效时间, 格式为 Unix Timestamp + DisableTime int + + // 创建时间, 格式为 Unix Timestamp + CreateTime int + + // 带宽包的临时带宽值, 单位Mbps + Bandwidth int + + // 带宽包所绑定弹性IP的资源ID + EIPId string + + // 带宽包所绑定弹性IP的详细信息,只有当EIPId对应双线IP时, EIPAddr的长度为2, 其他情况, EIPAddr长度均为1.参见 EIPAddrSet + EIPAddr []EIPAddrSet +} diff --git a/services/unet/types_unet_bandwidth_usage_eipset.go b/services/unet/types_unet_bandwidth_usage_eipset.go new file mode 100644 index 00000000..5a37ce65 --- /dev/null +++ b/services/unet/types_unet_bandwidth_usage_eipset.go @@ -0,0 +1,16 @@ +package unet + +/* + UnetBandwidthUsageEIPSet - DescribeBandwidthUsage + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UnetBandwidthUsageEIPSet struct { + + // 最近5分钟带宽用量, 单位Mbps + CurBandwidth float64 + + // 弹性IP资源ID + EIPId string +} diff --git a/services/unet/types_unet_eipaddr_set.go b/services/unet/types_unet_eipaddr_set.go new file mode 100644 index 00000000..0da957fd --- /dev/null +++ b/services/unet/types_unet_eipaddr_set.go @@ -0,0 +1,16 @@ +package unet + +/* + UnetEIPAddrSet - DescribeEIP + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UnetEIPAddrSet struct { + + // 运营商信息如: 电信: Telecom, 联通: Unicom, 国际: International, Duplet: 双线IP(电信+联通), BGP: Bgp + OperatorName string + + // IP地址 + IP string +} diff --git a/services/unet/types_unet_eipresource_set.go b/services/unet/types_unet_eipresource_set.go new file mode 100644 index 00000000..24bc7cbb --- /dev/null +++ b/services/unet/types_unet_eipresource_set.go @@ -0,0 +1,22 @@ +package unet + +/* + UnetEIPResourceSet - DescribeEIP + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UnetEIPResourceSet struct { + + // 已绑定的资源类型, 枚举值为: uhost, 云主机;vrouter:虚拟路由器;ulb:负载均衡器 + ResourceType string + + // 已绑定的资源名称 + ResourceName string + + // 已绑定资源的资源ID + ResourceId string + + // 弹性IP的资源ID + EIPId string +} diff --git a/services/unet/types_unet_eipset.go b/services/unet/types_unet_eipset.go new file mode 100644 index 00000000..670c9448 --- /dev/null +++ b/services/unet/types_unet_eipset.go @@ -0,0 +1,58 @@ +package unet + +/* + UnetEIPSet - DescribeEIP + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UnetEIPSet struct { + + // 弹性IP的资源ID + EIPId string + + // 外网出口权重, 默认为50, 范围[0-100] + Weight int + + // 带宽模式, 枚举值为: 0: 非共享带宽模式, 1: 共享带宽模式 + BandwidthType int + + // 弹性IP的带宽, 单位为Mbps, 当BandwidthType=1时, 该处显示为共享带宽值. 当BandwidthType=0时, 该处显示这个弹性IP的带宽. + Bandwidth int + + // 弹性IP的资源绑定状态, 枚举值为: used: 已绑定, free: 未绑定, freeze: 已冻结 + Status string + + // 付费方式, 枚举值为: Year, 按年付费; Month, 按月付费; Dynamic, 按小时付费; Trial, 试用. 按小时付费和试用这两种付费模式需要开通权限. + ChargeType string + + // 弹性IP的创建时间, 格式为Unix Timestamp + CreateTime int + + // 弹性IP的到期时间, 格式为Unix Timestamp + ExpireTime int + + // 弹性IP的详细信息列表, 具体结构见下方 UnetEIPResourceSet + Resource UnetEIPResourceSet + + // 弹性IP的详细信息列表, 具体结构见下方 UnetEIPAddrSet + EIPAddr []UnetEIPAddrSet + + // 弹性IP的名称,缺省值为 "EIP" + Name string + + // 弹性IP的业务组标识, 缺省值为 "Default" + Tag string + + // 弹性IP的备注, 缺省值为 "" + Remark string + + // 弹性IP的计费模式, 枚举值为: "Bandwidth", 带宽计费; "Traffic", 流量计费; "ShareBandwidth",共享带宽模式. 默认为 "Bandwidth". + PayMode string + + // 共享带宽信息 参见 ShareBandwidthSet + ShareBandwidthSet ShareBandwidthSet + + // 弹性IP是否到期 + Expire bool +} diff --git a/services/unet/types_unet_share_bandwidth_set.go b/services/unet/types_unet_share_bandwidth_set.go new file mode 100644 index 00000000..ddd27f51 --- /dev/null +++ b/services/unet/types_unet_share_bandwidth_set.go @@ -0,0 +1,37 @@ +package unet + +/* + UnetShareBandwidthSet - DescribeShareBandwidth + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type UnetShareBandwidthSet struct { + + // 共享带宽值(预付费)/共享带宽峰值(后付费), 单位Mbps + ShareBandwidth int + + // 共享带宽的资源ID + ShareBandwidthId string + + // 付费方式, 预付费:Year 按年,Month 按月,Dynamic 按需;后付费:PostPay(按月) + ChargeType string + + // 创建时间, 格式为Unix Timestamp + CreateTime int + + // 过期时间, 格式为Unix Timestamp + ExpireTime int + + // EIP信息,详情见 EIPSetData + EIPSet []EIPSetData + + // 共享带宽保底值(后付费) + BandwidthGuarantee int + + // 共享带宽后付费开始计费时间(后付费) + PostPayStartTime int + + // 共享带宽名称 + Name string +} diff --git a/services/unet/types_vipdetail_set.go b/services/unet/types_vipdetail_set.go new file mode 100644 index 00000000..66662e6d --- /dev/null +++ b/services/unet/types_vipdetail_set.go @@ -0,0 +1,31 @@ +package unet + +/* + VIPDetailSet - VIPDetailSet + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type VIPDetailSet struct { + + // 虚拟ip id + VIPId string + + // 创建时间 + CreateTime int + + // 地域 + Zone string + + // 真实主机ip + RealIp string + + // 虚拟ip + VIP string + + // 子网id + SubnetId string + + // VPC id + VPCId string +} diff --git a/services/unet/types_vipset.go b/services/unet/types_vipset.go new file mode 100644 index 00000000..14cf3f77 --- /dev/null +++ b/services/unet/types_vipset.go @@ -0,0 +1,19 @@ +package unet + +/* + VIPSet - VIPSet + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type VIPSet struct { + + // 虚拟ip + VIP string + + // 虚拟ip id + VIPId string + + // VPC id + VPCId string +} diff --git a/services/unet/un_bind_eip.go b/services/unet/un_bind_eip.go new file mode 100644 index 00000000..6d539eaf --- /dev/null +++ b/services/unet/un_bind_eip.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet UnBindEIP + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// UnBindEIPRequest is request schema for UnBindEIP action +type UnBindEIPRequest struct { + request.CommonBase + + // 弹性IP的资源Id + EIPId *string `required:"true"` + + // 弹性IP请求解绑的资源类型, 枚举值为: uhost: 云主机; vrouter: 虚拟路由器; ulb, 负载均衡器 upm: 物理机; hadoophost: 大数据集群;fortresshost:堡垒机;udockhost:容器;udhost:私有专区主机;natgw:natgw;udb:udb;vpngw:ipsec vpn;ucdr:云灾备;dbaudit:数据库审计; + ResourceType *string `required:"true"` + + // 弹性IP请求解绑的资源ID + ResourceId *string `required:"true"` +} + +// UnBindEIPResponse is response schema for UnBindEIP action +type UnBindEIPResponse struct { + response.CommonBase +} + +// NewUnBindEIPRequest will create request of UnBindEIP action. +func (c *UNetClient) NewUnBindEIPRequest() *UnBindEIPRequest { + req := &UnBindEIPRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// UnBindEIP - 将弹性IP从资源上解绑 +func (c *UNetClient) UnBindEIP(req *UnBindEIPRequest) (*UnBindEIPResponse, error) { + var err error + var res UnBindEIPResponse + + err = c.client.InvokeAction("UnBindEIP", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/update_eipattribute.go b/services/unet/update_eipattribute.go new file mode 100644 index 00000000..2c655dfe --- /dev/null +++ b/services/unet/update_eipattribute.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet UpdateEIPAttribute + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// UpdateEIPAttributeRequest is request schema for UpdateEIPAttribute action +type UpdateEIPAttributeRequest struct { + request.CommonBase + + // EIP资源ID + EIPId *string `required:"true"` + + // 名字(Name Tag Remark都为空则报错) + Name *string `required:"false"` + + // 业务 + Tag *string `required:"false"` + + // 备注 + Remark *string `required:"false"` +} + +// UpdateEIPAttributeResponse is response schema for UpdateEIPAttribute action +type UpdateEIPAttributeResponse struct { + response.CommonBase +} + +// NewUpdateEIPAttributeRequest will create request of UpdateEIPAttribute action. +func (c *UNetClient) NewUpdateEIPAttributeRequest() *UpdateEIPAttributeRequest { + req := &UpdateEIPAttributeRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// UpdateEIPAttribute - 更新弹性IP名称,业务组,备注等属性字段 +func (c *UNetClient) UpdateEIPAttribute(req *UpdateEIPAttributeRequest) (*UpdateEIPAttributeResponse, error) { + var err error + var res UpdateEIPAttributeResponse + + err = c.client.InvokeAction("UpdateEIPAttribute", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/update_firewall.go b/services/unet/update_firewall.go new file mode 100644 index 00000000..382c9556 --- /dev/null +++ b/services/unet/update_firewall.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet UpdateFirewall + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// UpdateFirewallRequest is request schema for UpdateFirewall action +type UpdateFirewallRequest struct { + request.CommonBase + + // 防火墙资源ID + FWId *string `required:"true"` + + // 防火墙规则,例如:TCP|22|192.168.1.1/22|DROP|LOW,第一个参数代表协议:第二个参数代表端口号,第三个参数为ip,第四个参数为ACCEPT(接受)和DROP(拒绝),第五个参数优先级:HIGH(高),MEDIUM(中),LOW(低) + Rule []string `required:"true"` +} + +// UpdateFirewallResponse is response schema for UpdateFirewall action +type UpdateFirewallResponse struct { + response.CommonBase + + // 防火墙id + FWId string +} + +// NewUpdateFirewallRequest will create request of UpdateFirewall action. +func (c *UNetClient) NewUpdateFirewallRequest() *UpdateFirewallRequest { + req := &UpdateFirewallRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// UpdateFirewall - 更新防火墙规则 +func (c *UNetClient) UpdateFirewall(req *UpdateFirewallRequest) (*UpdateFirewallResponse, error) { + var err error + var res UpdateFirewallResponse + + err = c.client.InvokeAction("UpdateFirewall", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/unet/update_firewall_attribute.go b/services/unet/update_firewall_attribute.go new file mode 100644 index 00000000..55eac0b6 --- /dev/null +++ b/services/unet/update_firewall_attribute.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api UNet UpdateFirewallAttribute + +package unet + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// UpdateFirewallAttributeRequest is request schema for UpdateFirewallAttribute action +type UpdateFirewallAttributeRequest struct { + request.CommonBase + + // 防火墙资源ID + FWId *string `required:"true"` + + // 防火墙名称,默认为空,为空则不做修改。Name,Tag,Remark必须填写1个及以上 + Name *string `required:"false"` + + // 防火墙业务组,默认为空,为空则不做修改。Name,Tag,Remark必须填写1个及以上 + Tag *string `required:"false"` + + // 防火墙备注,默认为空,为空则不做修改。Name,Tag,Remark必须填写1个及以上 + Remark *string `required:"false"` +} + +// UpdateFirewallAttributeResponse is response schema for UpdateFirewallAttribute action +type UpdateFirewallAttributeResponse struct { + response.CommonBase +} + +// NewUpdateFirewallAttributeRequest will create request of UpdateFirewallAttribute action. +func (c *UNetClient) NewUpdateFirewallAttributeRequest() *UpdateFirewallAttributeRequest { + req := &UpdateFirewallAttributeRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// UpdateFirewallAttribute - 更新防火墙规则 +func (c *UNetClient) UpdateFirewallAttribute(req *UpdateFirewallAttributeRequest) (*UpdateFirewallAttributeResponse, error) { + var err error + var res UpdateFirewallAttributeResponse + + err = c.client.InvokeAction("UpdateFirewallAttribute", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/add_vpcnetwork.go b/services/vpc/add_vpcnetwork.go new file mode 100644 index 00000000..20e8c3bc --- /dev/null +++ b/services/vpc/add_vpcnetwork.go @@ -0,0 +1,50 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC AddVPCNetwork + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// AddVPCNetworkRequest is request schema for AddVPCNetwork action +type AddVPCNetworkRequest struct { + request.CommonBase + + // 源VPC短ID + VPCId *string `required:"true"` + + // 增加网段 + Network []string `required:"true"` +} + +// AddVPCNetworkResponse is response schema for AddVPCNetwork action +type AddVPCNetworkResponse struct { + response.CommonBase +} + +// NewAddVPCNetworkRequest will create request of AddVPCNetwork action. +func (c *VPCClient) NewAddVPCNetworkRequest() *AddVPCNetworkRequest { + req := &AddVPCNetworkRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// AddVPCNetwork - 添加VPC网段 +func (c *VPCClient) AddVPCNetwork(req *AddVPCNetworkRequest) (*AddVPCNetworkResponse, error) { + var err error + var res AddVPCNetworkResponse + + err = c.client.InvokeAction("AddVPCNetwork", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/client.go b/services/vpc/client.go new file mode 100644 index 00000000..7adc0202 --- /dev/null +++ b/services/vpc/client.go @@ -0,0 +1,17 @@ +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" +) + +type VPCClient struct { + client *ucloud.Client +} + +func NewClient(config *ucloud.Config, credential *auth.Credential) *VPCClient { + client := ucloud.NewClient(config, credential) + return &VPCClient{ + client: client, + } +} diff --git a/services/vpc/create_subnet.go b/services/vpc/create_subnet.go new file mode 100644 index 00000000..08ed3f7a --- /dev/null +++ b/services/vpc/create_subnet.go @@ -0,0 +1,65 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC CreateSubnet + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateSubnetRequest is request schema for CreateSubnet action +type CreateSubnetRequest struct { + request.CommonBase + + // VPC资源ID + VPCId *string `required:"true"` + + // 子网网络地址,例如192.168.0.0 + Subnet *string `required:"true"` + + // 子网网络号位数,默认为24 + Netmask *int `required:"false"` + + // 子网名称,默认为Subnet + SubnetName *string `required:"false"` + + // 业务组名称,默认为Default + Tag *string `required:"false"` + + // 备注 + Remark *string `required:"false"` +} + +// CreateSubnetResponse is response schema for CreateSubnet action +type CreateSubnetResponse struct { + response.CommonBase + + // 子网ID + SubnetId string +} + +// NewCreateSubnetRequest will create request of CreateSubnet action. +func (c *VPCClient) NewCreateSubnetRequest() *CreateSubnetRequest { + req := &CreateSubnetRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateSubnet - 创建子网 +func (c *VPCClient) CreateSubnet(req *CreateSubnetRequest) (*CreateSubnetResponse, error) { + var err error + var res CreateSubnetResponse + + err = c.client.InvokeAction("CreateSubnet", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/create_vpc.go b/services/vpc/create_vpc.go new file mode 100644 index 00000000..15f58a2c --- /dev/null +++ b/services/vpc/create_vpc.go @@ -0,0 +1,62 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC CreateVPC + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateVPCRequest is request schema for CreateVPC action +type CreateVPCRequest struct { + request.CommonBase + + // VPC名称 + Name *string `required:"true"` + + // VPC网段 + Network []string `required:"true"` + + // 业务组名称 + Tag *string `required:"false"` + + // 备注 + Remark *string `required:"false"` + + // VPC类型 + Type *int `required:"false"` +} + +// CreateVPCResponse is response schema for CreateVPC action +type CreateVPCResponse struct { + response.CommonBase + + // VPC资源Id + VPCId string +} + +// NewCreateVPCRequest will create request of CreateVPC action. +func (c *VPCClient) NewCreateVPCRequest() *CreateVPCRequest { + req := &CreateVPCRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateVPC - 创建VPC +func (c *VPCClient) CreateVPC(req *CreateVPCRequest) (*CreateVPCResponse, error) { + var err error + var res CreateVPCResponse + + err = c.client.InvokeAction("CreateVPC", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/create_vpcintercom.go b/services/vpc/create_vpcintercom.go new file mode 100644 index 00000000..647605dc --- /dev/null +++ b/services/vpc/create_vpcintercom.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC CreateVPCIntercom + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// CreateVPCIntercomRequest is request schema for CreateVPCIntercom action +type CreateVPCIntercomRequest struct { + request.CommonBase + + // 源VPC短ID + VPCId *string `required:"true"` + + // 目的VPC短ID + DstVPCId *string `required:"true"` + + // 目的所在地域(如果目的VPC和源VPC不在同一个地域,两个地域需要建立跨域通道,且该字段必选) + DstRegion *string `required:"false"` + + // 目的项目ID + DstProjectId *string `required:"false"` +} + +// CreateVPCIntercomResponse is response schema for CreateVPCIntercom action +type CreateVPCIntercomResponse struct { + response.CommonBase +} + +// NewCreateVPCIntercomRequest will create request of CreateVPCIntercom action. +func (c *VPCClient) NewCreateVPCIntercomRequest() *CreateVPCIntercomRequest { + req := &CreateVPCIntercomRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(false) + return req +} + +// CreateVPCIntercom - 新建VPC互通关系 +func (c *VPCClient) CreateVPCIntercom(req *CreateVPCIntercomRequest) (*CreateVPCIntercomResponse, error) { + var err error + var res CreateVPCIntercomResponse + + err = c.client.InvokeAction("CreateVPCIntercom", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/delete_subnet.go b/services/vpc/delete_subnet.go new file mode 100644 index 00000000..57c90258 --- /dev/null +++ b/services/vpc/delete_subnet.go @@ -0,0 +1,47 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC DeleteSubnet + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeleteSubnetRequest is request schema for DeleteSubnet action +type DeleteSubnetRequest struct { + request.CommonBase + + // 子网ID + SubnetId *string `required:"true"` +} + +// DeleteSubnetResponse is response schema for DeleteSubnet action +type DeleteSubnetResponse struct { + response.CommonBase +} + +// NewDeleteSubnetRequest will create request of DeleteSubnet action. +func (c *VPCClient) NewDeleteSubnetRequest() *DeleteSubnetRequest { + req := &DeleteSubnetRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DeleteSubnet - 删除子网 +func (c *VPCClient) DeleteSubnet(req *DeleteSubnetRequest) (*DeleteSubnetResponse, error) { + var err error + var res DeleteSubnetResponse + + err = c.client.InvokeAction("DeleteSubnet", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/delete_vpc.go b/services/vpc/delete_vpc.go new file mode 100644 index 00000000..c1f64340 --- /dev/null +++ b/services/vpc/delete_vpc.go @@ -0,0 +1,47 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC DeleteVPC + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeleteVPCRequest is request schema for DeleteVPC action +type DeleteVPCRequest struct { + request.CommonBase + + // VPC资源Id + VPCId *string `required:"true"` +} + +// DeleteVPCResponse is response schema for DeleteVPC action +type DeleteVPCResponse struct { + response.CommonBase +} + +// NewDeleteVPCRequest will create request of DeleteVPC action. +func (c *VPCClient) NewDeleteVPCRequest() *DeleteVPCRequest { + req := &DeleteVPCRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DeleteVPC - 删除VPC +func (c *VPCClient) DeleteVPC(req *DeleteVPCRequest) (*DeleteVPCResponse, error) { + var err error + var res DeleteVPCResponse + + err = c.client.InvokeAction("DeleteVPC", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/delete_vpcintercom.go b/services/vpc/delete_vpcintercom.go new file mode 100644 index 00000000..a4cec838 --- /dev/null +++ b/services/vpc/delete_vpcintercom.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC DeleteVPCIntercom + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DeleteVPCIntercomRequest is request schema for DeleteVPCIntercom action +type DeleteVPCIntercomRequest struct { + request.CommonBase + + // 源VPC短ID + VPCId *string `required:"true"` + + // 目的VPC短ID + DstVPCId *string `required:"true"` + + // 目的所在地域 + DstRegion *string `required:"false"` + + // 目的项目ID(如果目的VPC和源VPC不在同一个地域,两个地域需要建立跨域通道,且该字段必选) + DstProjectId *string `required:"false"` +} + +// DeleteVPCIntercomResponse is response schema for DeleteVPCIntercom action +type DeleteVPCIntercomResponse struct { + response.CommonBase +} + +// NewDeleteVPCIntercomRequest will create request of DeleteVPCIntercom action. +func (c *VPCClient) NewDeleteVPCIntercomRequest() *DeleteVPCIntercomRequest { + req := &DeleteVPCIntercomRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DeleteVPCIntercom - 删除VPC互通关系 +func (c *VPCClient) DeleteVPCIntercom(req *DeleteVPCIntercomRequest) (*DeleteVPCIntercomResponse, error) { + var err error + var res DeleteVPCIntercomResponse + + err = c.client.InvokeAction("DeleteVPCIntercom", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/describe_subnet.go b/services/vpc/describe_subnet.go new file mode 100644 index 00000000..140652be --- /dev/null +++ b/services/vpc/describe_subnet.go @@ -0,0 +1,71 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC DescribeSubnet + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeSubnetRequest is request schema for DescribeSubnet action +type DescribeSubnetRequest struct { + request.CommonBase + + // 子网id数组,适用于一次查询多个子网信息 + SubnetIds []string `required:"false"` + + // 子网id,适用于一次查询一个子网信息 + SubnetId *string `required:"false"` + + // VPC资源id + VPCId *string `required:"false"` + + // 业务组名称,默认为Default + Tag *string `required:"false"` + + // 业务组 + BusinessId *string `required:"false"` + + // 默认为0 + Offset *int `required:"false"` + + // 默认为20 + Limit *int `required:"false"` +} + +// DescribeSubnetResponse is response schema for DescribeSubnet action +type DescribeSubnetResponse struct { + response.CommonBase + + // 子网总数量 + TotalCount int + + // 子网信息数组 + DataSet []VPCSubnetInfoSet +} + +// NewDescribeSubnetRequest will create request of DescribeSubnet action. +func (c *VPCClient) NewDescribeSubnetRequest() *DescribeSubnetRequest { + req := &DescribeSubnetRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeSubnet - 获取子网信息 +func (c *VPCClient) DescribeSubnet(req *DescribeSubnetRequest) (*DescribeSubnetResponse, error) { + var err error + var res DescribeSubnetResponse + + err = c.client.InvokeAction("DescribeSubnet", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/describe_subnet_resource.go b/services/vpc/describe_subnet_resource.go new file mode 100644 index 00000000..90e41d50 --- /dev/null +++ b/services/vpc/describe_subnet_resource.go @@ -0,0 +1,62 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC DescribeSubnetResource + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeSubnetResourceRequest is request schema for DescribeSubnetResource action +type DescribeSubnetResourceRequest struct { + request.CommonBase + + // 子网id + SubnetId *string `required:"true"` + + // 资源类型 + ResourceType *string `required:"false"` + + // 分页号 + Offset *int `required:"false"` + + // 单页limit + Limit *int `required:"false"` +} + +// DescribeSubnetResourceResponse is response schema for DescribeSubnetResource action +type DescribeSubnetResourceResponse struct { + response.CommonBase + + // 总数 + TotalCount int + + // 返回数据集 + DataSet []ResourceInfo +} + +// NewDescribeSubnetResourceRequest will create request of DescribeSubnetResource action. +func (c *VPCClient) NewDescribeSubnetResourceRequest() *DescribeSubnetResourceRequest { + req := &DescribeSubnetResourceRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeSubnetResource - 展示子网资源 +func (c *VPCClient) DescribeSubnetResource(req *DescribeSubnetResourceRequest) (*DescribeSubnetResourceResponse, error) { + var err error + var res DescribeSubnetResourceResponse + + err = c.client.InvokeAction("DescribeSubnetResource", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/describe_vpc.go b/services/vpc/describe_vpc.go new file mode 100644 index 00000000..f0177bdc --- /dev/null +++ b/services/vpc/describe_vpc.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC DescribeVPC + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeVPCRequest is request schema for DescribeVPC action +type DescribeVPCRequest struct { + request.CommonBase + + // VPCId + VPCIds []string `required:"false"` + + // 业务组名称 + Tag *string `required:"false"` +} + +// DescribeVPCResponse is response schema for DescribeVPC action +type DescribeVPCResponse struct { + response.CommonBase + + // vpc信息 + DataSet []VPCInfo +} + +// NewDescribeVPCRequest will create request of DescribeVPC action. +func (c *VPCClient) NewDescribeVPCRequest() *DescribeVPCRequest { + req := &DescribeVPCRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeVPC - 获取VPC信息 +func (c *VPCClient) DescribeVPC(req *DescribeVPCRequest) (*DescribeVPCResponse, error) { + var err error + var res DescribeVPCResponse + + err = c.client.InvokeAction("DescribeVPC", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/describe_vpcintercom.go b/services/vpc/describe_vpcintercom.go new file mode 100644 index 00000000..8ebb329b --- /dev/null +++ b/services/vpc/describe_vpcintercom.go @@ -0,0 +1,56 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC DescribeVPCIntercom + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// DescribeVPCIntercomRequest is request schema for DescribeVPCIntercom action +type DescribeVPCIntercomRequest struct { + request.CommonBase + + // VPC短ID + VPCId *string `required:"true"` + + // 目的地域 + DstRegion *string `required:"false"` + + // 目的项目ID + DstProjectId *string `required:"false"` +} + +// DescribeVPCIntercomResponse is response schema for DescribeVPCIntercom action +type DescribeVPCIntercomResponse struct { + response.CommonBase + + // 联通VPC信息数组 + DataSet []VPCIntercomInfo +} + +// NewDescribeVPCIntercomRequest will create request of DescribeVPCIntercom action. +func (c *VPCClient) NewDescribeVPCIntercomRequest() *DescribeVPCIntercomRequest { + req := &DescribeVPCIntercomRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// DescribeVPCIntercom - 获取VPC互通信息 +func (c *VPCClient) DescribeVPCIntercom(req *DescribeVPCIntercomRequest) (*DescribeVPCIntercomResponse, error) { + var err error + var res DescribeVPCIntercomResponse + + err = c.client.InvokeAction("DescribeVPCIntercom", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/services/vpc/types_resource_info.go b/services/vpc/types_resource_info.go new file mode 100644 index 00000000..bd295d2a --- /dev/null +++ b/services/vpc/types_resource_info.go @@ -0,0 +1,22 @@ +package vpc + +/* + ResourceInfo - 资源信息 + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type ResourceInfo struct { + + // 资源名称 + Name string + + // 资源id + ResourceId string + + // 创建时间 + ResourceType string + + // ip地址 + IP string +} diff --git a/services/vpc/types_vpcinfo.go b/services/vpc/types_vpcinfo.go new file mode 100644 index 00000000..ec41d70b --- /dev/null +++ b/services/vpc/types_vpcinfo.go @@ -0,0 +1,29 @@ +package vpc + +// VPCInfo - vpc信息 +type VPCInfo struct { + + // 业务组 + Tag string + + // 创建时间 + CreateTime int + + // vpc名称 + Name string + + // vpc地址空间 + Network []string + + // vpc地址空间信息 + NetworkInfo []VPCNetworkInfo + + // vpc中子网数量 + SubnetCount int + + // 更新时间 + UpdateTime int + + // vpc的资源ID + VPCId string +} diff --git a/services/vpc/types_vpcintercom_info.go b/services/vpc/types_vpcintercom_info.go new file mode 100644 index 00000000..f1803754 --- /dev/null +++ b/services/vpc/types_vpcintercom_info.go @@ -0,0 +1,28 @@ +package vpc + +/* + VPCIntercomInfo - + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type VPCIntercomInfo struct { + + // 项目Id + ProjectId string + + // VPC的地址空间 + Network []string + + // 所属地域 + DstRegion string + + // VPC名字 + Name string + + // VPCId + VPCId string + + // 业务组(未分组显示为 Default) + Tag string +} diff --git a/services/vpc/types_vpcnetwork_info.go b/services/vpc/types_vpcnetwork_info.go new file mode 100644 index 00000000..f150a673 --- /dev/null +++ b/services/vpc/types_vpcnetwork_info.go @@ -0,0 +1,11 @@ +package vpc + +// VPCNetworkInfo - vpc地址空间信息 +type VPCNetworkInfo struct { + + // 地址空间段 + Network string + + // 地址空间中子网数量 + SubnetCount int +} diff --git a/services/vpc/types_vpcsubnet_info_set.go b/services/vpc/types_vpcsubnet_info_set.go new file mode 100644 index 00000000..1dff1c05 --- /dev/null +++ b/services/vpc/types_vpcsubnet_info_set.go @@ -0,0 +1,55 @@ +package vpc + +/* + VPCSubnetInfoSet - DescribeSubnet + + this model is auto created by ucloud code generater for open api, + you can also see https://docs.ucloud.cn for detail. +*/ +type VPCSubnetInfoSet struct { + + // VPC id + VPCId string + + // VPC名称 + VPCName string + + // 子网id + SubnetId string + + // 子网名称 + SubnetName string + + // 地址 + Zone string + + // 名称 + Name string + + // 备注 + Remark string + + // Tag + Tag string + + // 子网类型 + SubnetType int + + // 子网网段 + Subnet string + + // 子网掩码 + Netmask string + + // 子网网关 + Gateway string + + // 创建时间 + CreateTime int + + // 虚拟路由 id + VRouterId string + + // 是否关联NATGW + HasNATGW bool +} diff --git a/services/vpc/update_subnet_attribute.go b/services/vpc/update_subnet_attribute.go new file mode 100644 index 00000000..46aac90b --- /dev/null +++ b/services/vpc/update_subnet_attribute.go @@ -0,0 +1,53 @@ +//Code is generated by ucloud code generator, don't modify it by hand, it will cause undefined behaviors. +//go:generate ucloud-gen-go-api VPC UpdateSubnetAttribute + +package vpc + +import ( + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// UpdateSubnetAttributeRequest is request schema for UpdateSubnetAttribute action +type UpdateSubnetAttributeRequest struct { + request.CommonBase + + // 子网ID + SubnetId *string `required:"true"` + + // 子网名称(如果Name不填写,Tag必须填写) + Name *string `required:"false"` + + // 业务组名称(如果Tag不填写,Name必须填写) + Tag *string `required:"false"` +} + +// UpdateSubnetAttributeResponse is response schema for UpdateSubnetAttribute action +type UpdateSubnetAttributeResponse struct { + response.CommonBase +} + +// NewUpdateSubnetAttributeRequest will create request of UpdateSubnetAttribute action. +func (c *VPCClient) NewUpdateSubnetAttributeRequest() *UpdateSubnetAttributeRequest { + req := &UpdateSubnetAttributeRequest{} + + // setup request with client config + c.client.SetupRequest(req) + + // setup retryable with default retry policy (retry for non-create action and common error) + req.SetRetryable(true) + return req +} + +// UpdateSubnetAttribute - 更新子网信息 +func (c *VPCClient) UpdateSubnetAttribute(req *UpdateSubnetAttributeRequest) (*UpdateSubnetAttributeResponse, error) { + var err error + var res UpdateSubnetAttributeResponse + + err = c.client.InvokeAction("UpdateSubnetAttribute", req, &res) + if err != nil { + return &res, err + } + + return &res, nil +} diff --git a/tests/set_149_test.go b/tests/set_149_test.go new file mode 100644 index 00000000..882ff589 --- /dev/null +++ b/tests/set_149_test.go @@ -0,0 +1,817 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet149(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Image_Id_ucloud", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + ctx.SetVar("saopaulo_image", "uimage-1bkjka") + + testSet149CreateUHostInstance00(&ctx) + testSet149CreateULB01(&ctx) + testSet149DescribeULB02(&ctx) + testSet149CreateVServer03(&ctx) + testSet149DescribeVServer04(&ctx) + testSet149AllocateBackendBatch05(&ctx) + testSet149DescribeVServer06(&ctx) + testSet149UpdateBackendAttribute07(&ctx) + testSet149ReleaseBackend08(&ctx) + testSet149DescribeVServer09(&ctx) + testSet149AllocateBackend10(&ctx) + testSet149DescribeVServer11(&ctx) + testSet149GetBackendMetricInfo12(&ctx) + testSet149GetVServerMetricInfo13(&ctx) + testSet149UpdateULBAttribute14(&ctx) + testSet149UpdateVServerAttribute15(&ctx) + testSet149DescribeVServer16(&ctx) + testSet149DeleteVServer17(&ctx) + testSet149DescribeVServer18(&ctx) + testSet149DeleteULB19(&ctx) + testSet149DeleteULB20(&ctx) + testSet149DeleteULB21(&ctx) + testSet149DescribeULBSimple22(&ctx) + testSet149PoweroffUHostInstance23(&ctx) + testSet149TerminateUHostInstance24(&ctx) +} + +func testSet149CreateUHostInstance00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("Image_Id_ucloud"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", "Y2VzaGkxMjMrKw==")) + + ctx.NoError(utest.SetReqValue(req, "CPU", "1")) + ctx.NoError(utest.SetReqValue(req, "Memory", "1024")) + + ctx.NoError(utest.SetReqValue(req, "Name", "ulb-host")) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", "0")) + + ctx.NoError(utest.SetReqValue(req, "Tag", "Default")) + + ctx.NoError(utest.SetReqValue(req, "TimemachineFeature", "No")) + ctx.NoError(utest.SetReqValue(req, "HotplugFeature", "false")) + + ctx.NoError(utest.SetReqValue(req, "UHostType", "Normal")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["UHostId_01"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) + ctx.Vars["IP_01"] = ctx.Must(utest.GetValue(resp, "IPs.0")) +} + +func testSet149CreateULB01(ctx *utest.TestContext) { + time.Sleep(time.Duration(180) * time.Second) + + req := ulbClient.NewCreateULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBName", "测试")) + ctx.NoError(utest.SetReqValue(req, "Tag", "Default")) + + ctx.NoError(utest.SetReqValue(req, "InnerMode", "No")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreateULB(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["ULBId"] = ctx.Must(utest.GetValue(resp, "ULBId")) +} + +func testSet149DescribeULB02(ctx *utest.TestContext) { + time.Sleep(time.Duration(3) * time.Second) + + req := ulbClient.NewDescribeULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + ctx.NoError(utest.SetReqValue(req, "Limit", "60")) + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeULB(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.ULBId", ctx.GetVar("ULBId"), "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149CreateVServer03(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewCreateVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerName", "vserver-test")) + ctx.NoError(utest.SetReqValue(req, "ListenType", "RequestProxy")) + ctx.NoError(utest.SetReqValue(req, "Protocol", "HTTP")) + ctx.NoError(utest.SetReqValue(req, "FrontendPort", "80")) + ctx.NoError(utest.SetReqValue(req, "Method", "Roundrobin")) + ctx.NoError(utest.SetReqValue(req, "PersistenceType", "UserDefined")) + ctx.NoError(utest.SetReqValue(req, "PersistenceInfo", "huangchao")) + ctx.NoError(utest.SetReqValue(req, "ClientTimeout", "60")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreateVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4107", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DescribeVServer04(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.ListenType", "RequestProxy", "str_eq"), + ctx.NewValidator("DataSet.0.VServerName", "vserver-test", "str_eq"), + ctx.NewValidator("DataSet.0.Protocol", "HTTP", "str_eq"), + ctx.NewValidator("DataSet.0.FrontendPort", "80", "str_eq"), + ctx.NewValidator("DataSet.0.Method", "Roundrobin", "str_eq"), + ctx.NewValidator("DataSet.0.ClientTimeout", "60", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["VServerId"] = ctx.Must(utest.GetValue(resp, "DataSet.0.VServerId")) +} + +func testSet149AllocateBackendBatch05(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewAllocateBackendBatchRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + + ctx.NoError(utest.SetReqValue(req, "Backends", ctx.Must(utest.ConcatWithVertical(ctx.GetVar("UHostId_01"), "UHost", "80", "1", ctx.GetVar("IP_01"))))) + ctx.NoError(utest.SetReqValue(req, "ApiVersion", "3")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.AllocateBackendBatch(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "63016", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DescribeVServer06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.ListenType", "RequestProxy", "str_eq"), + ctx.NewValidator("DataSet.0.VServerName", "vserver-test", "str_eq"), + ctx.NewValidator("DataSet.0.Protocol", "HTTP", "str_eq"), + ctx.NewValidator("DataSet.0.FrontendPort", "80", "str_eq"), + ctx.NewValidator("DataSet.0.Method", "Roundrobin", "str_eq"), + ctx.NewValidator("DataSet.0.ClientTimeout", "60", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["BackendId"] = ctx.Must(utest.GetValue(resp, "DataSet.0.BackendSet.0.BackendId")) +} + +func testSet149UpdateBackendAttribute07(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewUpdateBackendAttributeRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "BackendId", ctx.GetVar("BackendId"))) + ctx.NoError(utest.SetReqValue(req, "Port", "80")) + ctx.NoError(utest.SetReqValue(req, "Enabled", "0")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.UpdateBackendAttribute(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149ReleaseBackend08(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewReleaseBackendRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "BackendId", ctx.GetVar("BackendId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.ReleaseBackend(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4103", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DescribeVServer09(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.BackendSet", "0", "len_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149AllocateBackend10(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewAllocateBackendRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + ctx.NoError(utest.SetReqValue(req, "ResourceType", "UHost")) + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("UHostId_01"))) + ctx.NoError(utest.SetReqValue(req, "Port", "80")) + ctx.NoError(utest.SetReqValue(req, "Enabled", "1")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.AllocateBackend(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "63016", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DescribeVServer11(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.BackendSet", "1", "len_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149GetBackendMetricInfo12(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iulbClient.NewGetBackendMetricInfoRequest() + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + ctx.NoError(utest.SetReqValue(req, "BackendIds", ctx.GetVar("BackendId"))) + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iulbClient.GetBackendMetricInfo(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149GetVServerMetricInfo13(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iulbClient.NewGetVServerMetricInfoRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iulbClient.GetVServerMetricInfo(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "1", "str_eq"), + ctx.NewValidator("DataSet.0.VServerId", ctx.GetVar("VServerId"), "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149UpdateULBAttribute14(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewUpdateULBAttributeRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "Name", "测试-改")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.UpdateULBAttribute(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149UpdateVServerAttribute15(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewUpdateVServerAttributeRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + ctx.NoError(utest.SetReqValue(req, "VServerName", "vserver-gai")) + ctx.NoError(utest.SetReqValue(req, "Protocol", "HTTPS")) + ctx.NoError(utest.SetReqValue(req, "Method", "Source")) + ctx.NoError(utest.SetReqValue(req, "PersistenceType", "ServerInsert")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.UpdateVServerAttribute(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DescribeVServer16(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "1", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DeleteVServer17(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDeleteVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DeleteVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4103", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DescribeVServer18(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4103", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DeleteULB19(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDeleteULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DeleteULB(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4103", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DeleteULB20(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDeleteULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DeleteULB(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4103", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DeleteULB21(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDeleteULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DeleteULB(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4103", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149DescribeULBSimple22(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iulbClient.NewDescribeULBSimpleRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iulbClient.DescribeULBSimple(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4103", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149PoweroffUHostInstance23(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewPoweroffUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("UHostId_01"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.PoweroffUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet149TerminateUHostInstance24(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("UHostId_01"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_1839_test.go b/tests/set_1839_test.go new file mode 100644 index 00000000..b08fcaf5 --- /dev/null +++ b/tests/set_1839_test.go @@ -0,0 +1,876 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet1839(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Password", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=") + ctx.SetVar("CreateCPU", "1") + ctx.SetVar("CreateBootDisk", "20") + ctx.SetVar("ChargeType", "Month") + ctx.SetVar("CreateMem", "1024") + ctx.SetVar("CreateDiskspace", "0") + ctx.SetVar("ModifyTag", "newTag") + ctx.SetVar("ModifyName", "new-uhost-api-status-test") + ctx.SetVar("ModifyRemark", "newRemark") + ctx.SetVar("Name", "uhost-api-status-test") + ctx.SetVar("ImageID", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + + testSet1839GetUImagePrice00(&ctx) + testSet1839GetRestResource01(&ctx) + testSet1839CreateUHostInstance02(&ctx) + testSet1839DescribeUHostInstance03(&ctx) + testSet1839DescribeUHostLite04(&ctx) + testSet1839DescribeUHostRecycle05(&ctx) + testSet1839ModifyUHostInstanceTag06(&ctx) + testSet1839DescribeUHostInstance07(&ctx) + testSet1839ModifyUHostInstanceName08(&ctx) + testSet1839DescribeUHostInstance09(&ctx) + testSet1839ModifyUHostInstanceRemark10(&ctx) + testSet1839DescribeUHostInstance11(&ctx) + testSet1839DescribeUHostTags12(&ctx) + testSet1839GetUHostInstancePrice13(&ctx) + testSet1839GetUHostUpgradePrice14(&ctx) + testSet1839GetUHostRenewPrice15(&ctx) + testSet1839GetUHostInstanceVncInfo16(&ctx) + testSet1839DescribeResourceMetric17(&ctx) + testSet1839GetMetric18(&ctx) + testSet1839DescribeSecurityGroup19(&ctx) + testSet1839StopUHostInstance20(&ctx) + testSet1839DescribeUHostInstance21(&ctx) + testSet1839StartUHostInstance22(&ctx) + testSet1839DescribeUHostInstance23(&ctx) + testSet1839PoweroffUHostInstance24(&ctx) + testSet1839DescribeUHostInstance25(&ctx) + testSet1839TerminateUHostInstance26(&ctx) +} + +func testSet1839GetUImagePrice00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iuhostClient.NewGetUImagePriceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("ImageID"))) + ctx.NoError(utest.SetReqValue(req, "Count", "1")) + ctx.NoError(utest.SetReqValue(req, "ChargeType", ctx.GetVar("ChargeType"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.GetUImagePrice(req) + }, + Validators: []utest.TestValidator{ + // ctx.NewValidator("PriceSet.0.Price", "0", "ne"), + }, + MaxRetries: 3, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839GetRestResource01(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iuhostClient.NewGetRestResourceRequest() + + ctx.NoError(utest.SetReqValue(req, "ResourceType", "GPU")) + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.GetRestResource(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839CreateUHostInstance02(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("ImageID"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", ctx.GetVar("Password"))) + + ctx.NoError(utest.SetReqValue(req, "CPU", ctx.GetVar("CreateCPU"))) + ctx.NoError(utest.SetReqValue(req, "Memory", ctx.GetVar("CreateMem"))) + + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("Name"))) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", ctx.GetVar("CreateDiskspace"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", ctx.GetVar("ChargeType"))) + ctx.NoError(utest.SetReqValue(req, "Quantity", "1")) + + ctx.NoError(utest.SetReqValue(req, "BootDiskSpace", ctx.GetVar("CreateBootDisk"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["hostId"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet1839DescribeUHostInstance03(ctx *utest.TestContext) { + time.Sleep(time.Duration(20) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "1", "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("CreateCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("CreateDiskspace"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("Name"), "str_eq"), + // ctx.NewValidator("UHostSet.0.BasicImageId", ctx.GetVar("ImageID"), "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + }, + MaxRetries: 120, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeUHostLite04(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iuhostClient.NewDescribeUHostLiteRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DescribeUHostLite(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeUHostRecycle05(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iuhostClient.NewDescribeUHostRecycleRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DescribeUHostRecycle(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839ModifyUHostInstanceTag06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewModifyUHostInstanceTagRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + ctx.NoError(utest.SetReqValue(req, "Tag", ctx.GetVar("ModifyTag"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.ModifyUHostInstanceTag(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeUHostInstance07(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "1", "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("CreateCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("CreateDiskspace"), "str_eq"), + ctx.NewValidator("UHostSet.0.Tag", ctx.GetVar("ModifyTag"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("Name"), "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839ModifyUHostInstanceName08(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewModifyUHostInstanceNameRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("ModifyName"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.ModifyUHostInstanceName(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeUHostInstance09(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "1", "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("CreateCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("CreateDiskspace"), "str_eq"), + ctx.NewValidator("UHostSet.0.Tag", ctx.GetVar("ModifyTag"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("ModifyName"), "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839ModifyUHostInstanceRemark10(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewModifyUHostInstanceRemarkRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + ctx.NoError(utest.SetReqValue(req, "Remark", ctx.GetVar("ModifyRemark"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.ModifyUHostInstanceRemark(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeUHostInstance11(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "1", "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("CreateCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("CreateDiskspace"), "str_eq"), + ctx.NewValidator("UHostSet.0.Tag", ctx.GetVar("ModifyTag"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("ModifyName"), "str_eq"), + ctx.NewValidator("UHostSet.0.Remark", ctx.GetVar("ModifyRemark"), "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeUHostTags12(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewDescribeUHostTagsRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostTags(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839GetUHostInstancePrice13(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewGetUHostInstancePriceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("ImageID"))) + ctx.NoError(utest.SetReqValue(req, "CPU", "1")) + ctx.NoError(utest.SetReqValue(req, "Memory", "1024")) + ctx.NoError(utest.SetReqValue(req, "Count", "1")) + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Dynamic")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.GetUHostInstancePrice(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("PriceSet.0.Price", "0", "ne"), + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839GetUHostUpgradePrice14(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewGetUHostUpgradePriceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + ctx.NoError(utest.SetReqValue(req, "CPU", "8")) + ctx.NoError(utest.SetReqValue(req, "Memory", "8192")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.GetUHostUpgradePrice(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Price", "0", "ne"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839GetUHostRenewPrice15(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iuhostClient.NewGetUHostRenewPriceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.GetUHostRenewPrice(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("PriceSet.0.Price", "0", "ne"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839GetUHostInstanceVncInfo16(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewGetUHostInstanceVncInfoRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.GetUHostInstanceVncInfo(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeResourceMetric17(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iumonClient.NewDescribeResourceMetricRequest() + + ctx.NoError(utest.SetReqValue(req, "ResourceType", "uhost")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iumonClient.DescribeResourceMetric(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839GetMetric18(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iumonClient.NewGetMetricRequest() + + ctx.NoError(utest.SetReqValue(req, "ResourceType", "uhost")) + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "MetricName", "CPUUtilization")) + + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iumonClient.GetMetric(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "GetMetricResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeSecurityGroup19(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iunetClient.NewDescribeSecurityGroupRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iunetClient.DescribeSecurityGroup(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839StopUHostInstance20(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewStopUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StopUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "StopUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeUHostInstance21(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839StartUHostInstance22(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewStartUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StartUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "StartUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeUHostInstance23(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839PoweroffUHostInstance24(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewPoweroffUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.PoweroffUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "PoweroffUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839DescribeUHostInstance25(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1839TerminateUHostInstance26(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_1840_test.go b/tests/set_1840_test.go new file mode 100644 index 00000000..ac963ea7 --- /dev/null +++ b/tests/set_1840_test.go @@ -0,0 +1,471 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet1840(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Password", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=") + ctx.SetVar("SnapshotSysName", "snapshot-ARK-SYS-01") + ctx.SetVar("SnapshotSysDesc", "snapshot-ARK-SYS-01-desc") + ctx.SetVar("SnapDiskType", "LocalBoot") + ctx.SetVar("SnapshotDataNameModify", "snapshot-ARK-DATA-01-modify") + ctx.SetVar("SnapshotDataDescModify", "snapshot-ARK-DATA-01-desc-Modify") + ctx.SetVar("UhostName", "uhost-snapshot-ARK-auto-api-1") + ctx.SetVar("SnapshotDataName", "snapshot-ARK-DATA-01") + ctx.SetVar("SnapshotDataDesc", "snapshot-ARK-DATA-01-desc") + ctx.SetVar("CreateFromTimeMachinePassword", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=") + ctx.SetVar("ImageID", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + + testSet1840CreateUHostInstance00(&ctx) + testSet1840DescribeUHostInstance01(&ctx) + testSet1840StopUHostInstance02(&ctx) + testSet1840DescribeUHostInstance03(&ctx) + testSet1840UpgradeToArkUHostInstance04(&ctx) + testSet1840DescribeUHostInstance05(&ctx) + testSet1840StartUHostInstance06(&ctx) + testSet1840DescribeUHostInstance07(&ctx) + testSet1840DescribeUhostTmMeta08(&ctx) + testSet1840DescribeVDiskTmList09(&ctx) + testSet1840DescribeVDiskTmList10(&ctx) + testSet1840StopUHostInstance11(&ctx) + testSet1840DescribeUHostInstance12(&ctx) + testSet1840TerminateUHostInstance13(&ctx) +} + +func testSet1840CreateUHostInstance00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("ImageID"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", ctx.GetVar("Password"))) + + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("UhostName"))) + + ctx.NoError(utest.SetReqValue(req, "TimemachineFeature", "no")) + ctx.NoError(utest.SetReqValue(req, "HotplugFeature", "false")) + + ctx.NoError(utest.SetReqValue(req, "GPU", 0)) // TODO: check + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["hostId"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet1840DescribeUHostInstance01(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + ctx.NewValidator("UHostSet.0.TimemachineFeature", "no", "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + }, + MaxRetries: 100, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840StopUHostInstance02(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewStopUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StopUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "StopUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840DescribeUHostInstance03(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840UpgradeToArkUHostInstance04(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewUpgradeToArkUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.UpgradeToArkUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "UpgradeToArkUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840DescribeUHostInstance05(ctx *utest.TestContext) { + time.Sleep(time.Duration(100) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + ctx.NewValidator("UHostSet.0.TimemachineFeature", "yes", "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + ctx.NewValidator("UHostSet.0.DiskSet.0.BackupType", "DATAARK", "str_eq"), + }, + MaxRetries: 120, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840StartUHostInstance06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewStartUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StartUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "StartUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840DescribeUHostInstance07(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + ctx.NewValidator("UHostSet.0.TimemachineFeature", "yes", "str_eq"), + ctx.NewValidator("UHostSet.0.DiskSet.0.BackupType", "DATAARK", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840DescribeUhostTmMeta08(ctx *utest.TestContext) { + time.Sleep(time.Duration(100) * time.Second) + + req := iudataarkClient.NewDescribeUhostTmMetaRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UhostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudataarkClient.DescribeUhostTmMeta(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeUhostTmMetaResponse", "str_eq"), + ctx.NewValidator("UtmStatus", "normal", "str_eq"), + }, + MaxRetries: 60, + RetryInterval: 60 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["VdiskIdSys"] = ctx.Must(utest.GetValue(resp, "DataSet.0.VdiskId")) + ctx.Vars["VdiskIdData"] = ctx.Must(utest.GetValue(resp, "DataSet.1.VdiskId")) +} + +func testSet1840DescribeVDiskTmList09(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudataarkClient.NewDescribeVDiskTmListRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "VDiskId", ctx.GetVar("VdiskIdSys"))) + ctx.NoError(utest.SetReqValue(req, "SnapshotType", "all")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudataarkClient.DescribeVDiskTmList(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeVDiskTmListResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840DescribeVDiskTmList10(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudataarkClient.NewDescribeVDiskTmListRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "VDiskId", ctx.GetVar("VdiskIdData"))) + ctx.NoError(utest.SetReqValue(req, "SnapshotType", "all")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudataarkClient.DescribeVDiskTmList(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeVDiskTmListResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840StopUHostInstance11(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewStopUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StopUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "StopUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840DescribeUHostInstance12(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet1840TerminateUHostInstance13(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "TerminateUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_220_test.go b/tests/set_220_test.go new file mode 100644 index 00000000..3a45e0bf --- /dev/null +++ b/tests/set_220_test.go @@ -0,0 +1,413 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet220(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Image_Id_cloud", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + ctx.SetVar("saopaulo_image", "uimage-1bkjka") + + testSet220CreateUHostInstance00(&ctx) + testSet220CreateULB01(&ctx) + testSet220CreateVServer02(&ctx) + testSet220DescribeVServer03(&ctx) + testSet220AllocateBackend04(&ctx) + testSet220DescribeVServer05(&ctx) + testSet220CreatePolicy06(&ctx) + testSet220UpdatePolicy07(&ctx) + testSet220DeletePolicy08(&ctx) + testSet220DeleteULB09(&ctx) + testSet220PoweroffUHostInstance10(&ctx) + testSet220TerminateUHostInstance11(&ctx) +} + +func testSet220CreateUHostInstance00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("Image_Id_cloud"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", "Y2VzaGkxMjMrKw==")) + + ctx.NoError(utest.SetReqValue(req, "CPU", "1")) + ctx.NoError(utest.SetReqValue(req, "Memory", "1024")) + + ctx.NoError(utest.SetReqValue(req, "Name", "ulb-host")) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", "0")) + + ctx.NoError(utest.SetReqValue(req, "Tag", "Default")) + + ctx.NoError(utest.SetReqValue(req, "TimemachineFeature", "No")) + ctx.NoError(utest.SetReqValue(req, "HotplugFeature", "false")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["UHostId_01"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) + ctx.Vars["IP_01"] = ctx.Must(utest.GetValue(resp, "IPs.0")) +} + +func testSet220CreateULB01(ctx *utest.TestContext) { + time.Sleep(time.Duration(180) * time.Second) + + req := ulbClient.NewCreateULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBName", "测试")) + ctx.NoError(utest.SetReqValue(req, "Tag", "Default")) + + ctx.NoError(utest.SetReqValue(req, "InnerMode", "No")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreateULB(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["ULBId"] = ctx.Must(utest.GetValue(resp, "ULBId")) +} + +func testSet220CreateVServer02(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := ulbClient.NewCreateVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerName", "vserver-test")) + ctx.NoError(utest.SetReqValue(req, "ListenType", "RequestProxy")) + ctx.NoError(utest.SetReqValue(req, "Protocol", "HTTP")) + ctx.NoError(utest.SetReqValue(req, "FrontendPort", "80")) + ctx.NoError(utest.SetReqValue(req, "Method", "Roundrobin")) + ctx.NoError(utest.SetReqValue(req, "PersistenceType", "UserDefined")) + ctx.NoError(utest.SetReqValue(req, "PersistenceInfo", "huangchao")) + ctx.NoError(utest.SetReqValue(req, "ClientTimeout", "60")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreateVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4107", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet220DescribeVServer03(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet", "1", "len_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["VServerId"] = ctx.Must(utest.GetValue(resp, "DataSet.0.VServerId")) +} + +func testSet220AllocateBackend04(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := ulbClient.NewAllocateBackendRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + ctx.NoError(utest.SetReqValue(req, "ResourceType", "UHost")) + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("UHostId_01"))) + ctx.NoError(utest.SetReqValue(req, "Port", "80")) + ctx.NoError(utest.SetReqValue(req, "Enabled", "1")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.AllocateBackend(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "63016", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet220DescribeVServer05(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.BackendSet", "1", "len_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["BackendId"] = ctx.Must(utest.GetValue(resp, "DataSet.0.BackendSet.0.BackendId")) +} + +func testSet220CreatePolicy06(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := ulbClient.NewCreatePolicyRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + ctx.NoError(utest.SetReqValue(req, "BackendId", ctx.GetVar("BackendId"))) + ctx.NoError(utest.SetReqValue(req, "Match", "www.test.com")) + ctx.NoError(utest.SetReqValue(req, "Type", "Domain")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreatePolicy(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["PolicyId"] = ctx.Must(utest.GetValue(resp, "PolicyId")) +} + +func testSet220UpdatePolicy07(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := ulbClient.NewUpdatePolicyRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + ctx.NoError(utest.SetReqValue(req, "PolicyId", ctx.GetVar("PolicyId"))) + ctx.NoError(utest.SetReqValue(req, "BackendId", ctx.GetVar("BackendId"))) + ctx.NoError(utest.SetReqValue(req, "Type", "Domain")) + ctx.NoError(utest.SetReqValue(req, "Match", "www.testgai.com")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.UpdatePolicy(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet220DeletePolicy08(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := ulbClient.NewDeletePolicyRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "PolicyId", ctx.GetVar("PolicyId"))) + + ctx.NoError(utest.SetReqValue(req, "VServerId", ctx.GetVar("VServerId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DeletePolicy(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet220DeleteULB09(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := ulbClient.NewDeleteULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DeleteULB(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet220PoweroffUHostInstance10(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := uhostClient.NewPoweroffUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("UHostId_01"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.PoweroffUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet220TerminateUHostInstance11(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("UHostId_01"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_227_test.go b/tests/set_227_test.go new file mode 100644 index 00000000..b1ac557d --- /dev/null +++ b/tests/set_227_test.go @@ -0,0 +1,273 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet227(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + testSet227CreateULB00(&ctx) + testSet227CreateVServer01(&ctx) + testSet227DescribeVServer02(&ctx) + testSet227CreateVServer03(&ctx) + testSet227DescribeVServer04(&ctx) + testSet227CreateVServer05(&ctx) + testSet227DescribeVServer06(&ctx) + testSet227DeleteULB07(&ctx) +} + +func testSet227CreateULB00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewCreateULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBName", "测试")) + ctx.NoError(utest.SetReqValue(req, "Tag", "Default")) + + ctx.NoError(utest.SetReqValue(req, "OuterMode", "Yes")) + ctx.NoError(utest.SetReqValue(req, "InnerMode", "No")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreateULB(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["ULBId_outer"] = ctx.Must(utest.GetValue(resp, "ULBId")) +} + +func testSet227CreateVServer01(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := ulbClient.NewCreateVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId_outer"))) + ctx.NoError(utest.SetReqValue(req, "VServerName", "vserver-http")) + ctx.NoError(utest.SetReqValue(req, "ListenType", "RequestProxy")) + ctx.NoError(utest.SetReqValue(req, "Protocol", "HTTP")) + ctx.NoError(utest.SetReqValue(req, "FrontendPort", "80")) + ctx.NoError(utest.SetReqValue(req, "Method", "Roundrobin")) + ctx.NoError(utest.SetReqValue(req, "PersistenceType", "ServerInsert")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreateVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4107", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet227DescribeVServer02(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId_outer"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet227CreateVServer03(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := ulbClient.NewCreateVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId_outer"))) + ctx.NoError(utest.SetReqValue(req, "VServerName", "vserver-https")) + ctx.NoError(utest.SetReqValue(req, "ListenType", "RequestProxy")) + ctx.NoError(utest.SetReqValue(req, "Protocol", "HTTPS")) + ctx.NoError(utest.SetReqValue(req, "FrontendPort", "443")) + ctx.NoError(utest.SetReqValue(req, "Method", "Source")) + ctx.NoError(utest.SetReqValue(req, "PersistenceType", "UserDefined")) + ctx.NoError(utest.SetReqValue(req, "PersistenceInfo", "huangchao")) + ctx.NoError(utest.SetReqValue(req, "ClientTimeout", "60")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreateVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4107", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet227DescribeVServer04(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId_outer"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet227CreateVServer05(ctx *utest.TestContext) { + time.Sleep(time.Duration(20) * time.Second) + + req := ulbClient.NewCreateVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId_outer"))) + ctx.NoError(utest.SetReqValue(req, "VServerName", "vserver-https")) + ctx.NoError(utest.SetReqValue(req, "ListenType", "RequestProxy")) + ctx.NoError(utest.SetReqValue(req, "Protocol", "TCP")) + ctx.NoError(utest.SetReqValue(req, "FrontendPort", "1024")) + ctx.NoError(utest.SetReqValue(req, "Method", "Source")) + ctx.NoError(utest.SetReqValue(req, "PersistenceType", "None")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreateVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "4107", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet227DescribeVServer06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewDescribeVServerRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId_outer"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DescribeVServer(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet227DeleteULB07(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := ulbClient.NewDeleteULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId_outer"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DeleteULB(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_230_test.go b/tests/set_230_test.go new file mode 100644 index 00000000..6b24bd19 --- /dev/null +++ b/tests/set_230_test.go @@ -0,0 +1,332 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet230(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("sbw_name", "sbw_api_auto") + ctx.SetVar("sbw_chargetype", "Month") + ctx.SetVar("sbw_bw", "22") + ctx.SetVar("resize_bw", "25") + ctx.SetVar("Region", "cn-bj2") + ctx.SetVar("eip_operatorname", "Bgp") + ctx.SetVar("eip_bw", "2") + + testSet230AllocateShareBandwidth00(&ctx) + testSet230AllocateEIP01(&ctx) + testSet230AssociateEIPWithShareBandwidth02(&ctx) + testSet230DescribeShareBandwidthPrice03(&ctx) + testSet230DescribeShareBandwidth04(&ctx) + testSet230ResizeShareBandwidth05(&ctx) + testSet230DescribeShareBandwidth06(&ctx) + testSet230DisassociateEIPWithShareBandwidth07(&ctx) + testSet230ReleaseEIP08(&ctx) + testSet230ReleaseShareBandwidth09(&ctx) +} + +func testSet230AllocateShareBandwidth00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewAllocateShareBandwidthRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("sbw_name"))) + ctx.NoError(utest.SetReqValue(req, "ChargeType", ctx.GetVar("sbw_chargetype"))) + ctx.NoError(utest.SetReqValue(req, "ShareBandwidth", ctx.GetVar("sbw_bw"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.AllocateShareBandwidth(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["sbw_id"] = ctx.Must(utest.GetValue(resp, "ShareBandwidthId")) +} + +func testSet230AllocateEIP01(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewAllocateEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "OperatorName", ctx.GetVar("eip_operatorname"))) + ctx.NoError(utest.SetReqValue(req, "Bandwidth", ctx.GetVar("eip_bw"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + + ctx.NoError(utest.SetReqValue(req, "PayMode", "Traffic")) + + ctx.NoError(utest.SetReqValue(req, "Name", "eip_auto")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.AllocateEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["eip_id"] = ctx.Must(utest.GetValue(resp, "EIPSet.0.EIPId")) +} + +func testSet230AssociateEIPWithShareBandwidth02(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := unetClient.NewAssociateEIPWithShareBandwidthRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPIds", ctx.GetVar("eip_id"))) + ctx.NoError(utest.SetReqValue(req, "ShareBandwidthId", ctx.GetVar("sbw_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.AssociateEIPWithShareBandwidth(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet230DescribeShareBandwidthPrice03(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iunetClient.NewDescribeShareBandwidthPriceRequest() + + ctx.NoError(utest.SetReqValue(req, "ChargeType", ctx.GetVar("sbw_chargetype"))) + ctx.NoError(utest.SetReqValue(req, "ShareBandwidth", ctx.GetVar("sbw_bw"))) + ctx.NoError(utest.SetReqValue(req, "Quantity", "1")) + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iunetClient.DescribeShareBandwidthPrice(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalPrice", "0", "gt"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet230DescribeShareBandwidth04(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewDescribeShareBandwidthRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "ShareBandwidthIds", ctx.GetVar("sbw_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeShareBandwidth(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.ShareBandwidthId", ctx.GetVar("sbw_id"), "str_eq"), + ctx.NewValidator("DataSet.0.ShareBandwidth", ctx.GetVar("sbw_bw"), "str_eq"), + ctx.NewValidator("DataSet.0.ChargeType", ctx.GetVar("sbw_chargetype"), "str_eq"), + ctx.NewValidator("DataSet.0.Name", ctx.GetVar("sbw_name"), "str_eq"), + ctx.NewValidator("TotalCount", "1", "str_eq"), + ctx.NewValidator("DataSet.0.EIPSet.0.EIPAddr.0.OperatorName", ctx.GetVar("eip_operatorname"), "str_eq"), + ctx.NewValidator("DataSet.0.EIPSet.0.EIPId", ctx.GetVar("eip_id"), "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet230ResizeShareBandwidth05(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewResizeShareBandwidthRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "ShareBandwidth", ctx.GetVar("resize_bw"))) + ctx.NoError(utest.SetReqValue(req, "ShareBandwidthId", ctx.GetVar("sbw_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.ResizeShareBandwidth(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet230DescribeShareBandwidth06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewDescribeShareBandwidthRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "ShareBandwidthIds", ctx.GetVar("sbw_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeShareBandwidth(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.ShareBandwidth", ctx.GetVar("resize_bw"), "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet230DisassociateEIPWithShareBandwidth07(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewDisassociateEIPWithShareBandwidthRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPIds", ctx.GetVar("eip_id"))) + ctx.NoError(utest.SetReqValue(req, "ShareBandwidthId", ctx.GetVar("sbw_id"))) + ctx.NoError(utest.SetReqValue(req, "Bandwidth", ctx.GetVar("eip_bw"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DisassociateEIPWithShareBandwidth(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet230ReleaseEIP08(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := unetClient.NewReleaseEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("eip_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.ReleaseEIP(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet230ReleaseShareBandwidth09(ctx *utest.TestContext) { + time.Sleep(time.Duration(3) * time.Second) + + req := unetClient.NewReleaseShareBandwidthRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "ShareBandwidthId", ctx.GetVar("sbw_id"))) + ctx.NoError(utest.SetReqValue(req, "EIPBandwidth", "2")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.ReleaseShareBandwidth(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_268_test.go b/tests/set_268_test.go new file mode 100644 index 00000000..42f0734a --- /dev/null +++ b/tests/set_268_test.go @@ -0,0 +1,388 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet268(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Region", "cn-bj2") + ctx.SetVar("eip_bw", "2") + ctx.SetVar("bwp1_bw", "3") + ctx.SetVar("eip_operatorname", "Bgp") + ctx.SetVar("bwp2_bw", "4") + + testSet268AllocateEIP00(&ctx) + testSet268CreateULB01(&ctx) + testSet268BindEIP02(&ctx) + testSet268CreateBandwidthPackage03(&ctx) + testSet268DescribeBandwidthPackage04(&ctx) + testSet268DeleteBandwidthPackage05(&ctx) + testSet268CreateBandwidthPackage06(&ctx) + testSet268DescribeBandwidthPackage07(&ctx) + testSet268DeleteBandwidthPackage08(&ctx) + testSet268UnBindEIP09(&ctx) + testSet268DeleteULB10(&ctx) + testSet268ReleaseEIP11(&ctx) +} + +func testSet268AllocateEIP00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewAllocateEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "OperatorName", ctx.GetVar("eip_operatorname"))) + ctx.NoError(utest.SetReqValue(req, "Bandwidth", ctx.GetVar("eip_bw"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + + ctx.NoError(utest.SetReqValue(req, "PayMode", "Bandwidth")) + + ctx.NoError(utest.SetReqValue(req, "Name", "eip_auto")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.AllocateEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["eip_id"] = ctx.Must(utest.GetValue(resp, "EIPSet.0.EIPId")) +} + +func testSet268CreateULB01(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := ulbClient.NewCreateULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBName", "ulb_for_bwp")) + + ctx.NoError(utest.SetReqValue(req, "OuterMode", "Yes")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreateULB(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["ulb_id"] = ctx.Must(utest.GetValue(resp, "ULBId")) +} + +func testSet268BindEIP02(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewBindEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("eip_id"))) + ctx.NoError(utest.SetReqValue(req, "ResourceType", "ulb")) + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("ulb_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.BindEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet268CreateBandwidthPackage03(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewCreateBandwidthPackageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Bandwidth", ctx.GetVar("bwp1_bw"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("eip_id"))) + ctx.NoError(utest.SetReqValue(req, "TimeRange", "2")) + ctx.NoError(utest.SetReqValue(req, "EnableTime", ctx.Must(utest.Calculate("+", "30", ctx.Must(utest.GetTimestamp("10")))))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.CreateBandwidthPackage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["bwp_id1"] = ctx.Must(utest.GetValue(resp, "BandwidthPackageId")) +} + +func testSet268DescribeBandwidthPackage04(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := unetClient.NewDescribeBandwidthPackageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Limit", "1")) + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeBandwidthPackage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSets.0.EIPId", ctx.GetVar("eip_id"), "str_eq"), + ctx.NewValidator("DataSets.0.Bandwidth", ctx.GetVar("bwp1_bw"), "str_eq"), + ctx.NewValidator("DataSets.0.BandwidthPackageId", ctx.GetVar("bwp_id1"), "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet268DeleteBandwidthPackage05(ctx *utest.TestContext) { + time.Sleep(time.Duration(3) * time.Second) + + req := unetClient.NewDeleteBandwidthPackageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "BandwidthPackageId", ctx.GetVar("bwp_id1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DeleteBandwidthPackage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet268CreateBandwidthPackage06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewCreateBandwidthPackageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Bandwidth", ctx.GetVar("bwp2_bw"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("eip_id"))) + ctx.NoError(utest.SetReqValue(req, "TimeRange", "1")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.CreateBandwidthPackage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["bwp_id2"] = ctx.Must(utest.GetValue(resp, "BandwidthPackageId")) +} + +func testSet268DescribeBandwidthPackage07(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := unetClient.NewDescribeBandwidthPackageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Limit", "1")) + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeBandwidthPackage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSets.0.EIPId", ctx.GetVar("eip_id"), "str_eq"), + ctx.NewValidator("DataSets.0.Bandwidth", ctx.GetVar("bwp2_bw"), "str_eq"), + ctx.NewValidator("DataSets.0.BandwidthPackageId", ctx.GetVar("bwp_id2"), "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet268DeleteBandwidthPackage08(ctx *utest.TestContext) { + time.Sleep(time.Duration(3) * time.Second) + + req := unetClient.NewDeleteBandwidthPackageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "BandwidthPackageId", ctx.GetVar("bwp_id2"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DeleteBandwidthPackage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet268UnBindEIP09(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewUnBindEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("eip_id"))) + ctx.NoError(utest.SetReqValue(req, "ResourceType", "ulb")) + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("ulb_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.UnBindEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet268DeleteULB10(ctx *utest.TestContext) { + time.Sleep(time.Duration(3) * time.Second) + + req := ulbClient.NewDeleteULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ulb_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DeleteULB(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet268ReleaseEIP11(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := unetClient.NewReleaseEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("eip_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.ReleaseEIP(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_279_test.go b/tests/set_279_test.go new file mode 100644 index 00000000..90490394 --- /dev/null +++ b/tests/set_279_test.go @@ -0,0 +1,566 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet279(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Image_Id", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + + testSet279CreateUHostInstance00(&ctx) + testSet279CreateULB01(&ctx) + testSet279AllocateEIP02(&ctx) + testSet279DescribeEIP03(&ctx) + testSet279UpdateEIPAttribute04(&ctx) + testSet279GetEIPPrice05(&ctx) + testSet279BindEIP06(&ctx) + testSet279ModifyEIPBandwidth07(&ctx) + testSet279SetEIPPayMode08(&ctx) + testSet279ModifyEIPWeight09(&ctx) + testSet279UnBindEIP10(&ctx) + testSet279BindEIP11(&ctx) + testSet279UnBindEIP12(&ctx) + testSet279ReleaseEIP13(&ctx) + testSet279DescribeEIP14(&ctx) + testSet279DeleteULB15(&ctx) + testSet279PoweroffUHostInstance16(&ctx) + testSet279TerminateUHostInstance17(&ctx) +} + +func testSet279CreateUHostInstance00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + ctx.NoError(utest.SetReqValue(req, "Name", "eip-s1-bgp")) + ctx.NoError(utest.SetReqValue(req, "Tag", "Default")) + + ctx.NoError(utest.SetReqValue(req, "CPU", "1")) + ctx.NoError(utest.SetReqValue(req, "Memory", "1024")) + + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("Image_Id"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", "Y2VzaGkxMjMrKw==")) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", "0")) + + ctx.NoError(utest.SetReqValue(req, "TimemachineFeature", "No")) + ctx.NoError(utest.SetReqValue(req, "HotplugFeature", "false")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostIds", "0", "len_ge"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["UHostId"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet279CreateULB01(ctx *utest.TestContext) { + time.Sleep(time.Duration(120) * time.Second) + + req := ulbClient.NewCreateULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBName", "ulb-eip")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.CreateULB(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["ULBId"] = ctx.Must(utest.GetValue(resp, "ULBId")) +} + +func testSet279AllocateEIP02(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewAllocateEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "OperatorName", "Bgp")) + ctx.NoError(utest.SetReqValue(req, "Bandwidth", "2")) + ctx.NoError(utest.SetReqValue(req, "Tag", "Default")) + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Dynamic")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "1")) + ctx.NoError(utest.SetReqValue(req, "PayMode", "Bandwidth")) + + ctx.NoError(utest.SetReqValue(req, "Name", "eip-bgp-01")) + ctx.NoError(utest.SetReqValue(req, "Remark", "test")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.AllocateEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["EIPId_01"] = ctx.Must(utest.GetValue(resp, "EIPSet.0.EIPId")) +} + +func testSet279DescribeEIP03(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewDescribeEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPIds", ctx.GetVar("EIPId_01"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279UpdateEIPAttribute04(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewUpdateEIPAttributeRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("EIPId_01"))) + ctx.NoError(utest.SetReqValue(req, "Name", "eip-auto-gai")) + ctx.NoError(utest.SetReqValue(req, "Tag", "huangchao")) + ctx.NoError(utest.SetReqValue(req, "Remark", "test-gai")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.UpdateEIPAttribute(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279GetEIPPrice05(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewGetEIPPriceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "OperatorName", "Bgp")) + ctx.NoError(utest.SetReqValue(req, "Bandwidth", "2")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.GetEIPPrice(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279BindEIP06(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewBindEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("EIPId_01"))) + ctx.NoError(utest.SetReqValue(req, "ResourceType", "ulb")) + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.BindEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279ModifyEIPBandwidth07(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewModifyEIPBandwidthRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("EIPId_01"))) + ctx.NoError(utest.SetReqValue(req, "Bandwidth", "3")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.ModifyEIPBandwidth(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279SetEIPPayMode08(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewSetEIPPayModeRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("EIPId_01"))) + ctx.NoError(utest.SetReqValue(req, "PayMode", "Traffic")) + ctx.NoError(utest.SetReqValue(req, "Bandwidth", "2")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.SetEIPPayMode(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279ModifyEIPWeight09(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewModifyEIPWeightRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("EIPId_01"))) + ctx.NoError(utest.SetReqValue(req, "Weight", "100")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.ModifyEIPWeight(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279UnBindEIP10(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewUnBindEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("EIPId_01"))) + ctx.NoError(utest.SetReqValue(req, "ResourceType", "ulb")) + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.UnBindEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279BindEIP11(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := unetClient.NewBindEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("EIPId_01"))) + ctx.NoError(utest.SetReqValue(req, "ResourceType", "uhost")) + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("UHostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.BindEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279UnBindEIP12(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := unetClient.NewUnBindEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("EIPId_01"))) + ctx.NoError(utest.SetReqValue(req, "ResourceType", "uhost")) + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("UHostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.UnBindEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279ReleaseEIP13(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := unetClient.NewReleaseEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPId", ctx.GetVar("EIPId_01"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.ReleaseEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "8039", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279DescribeEIP14(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewDescribeEIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "EIPIds", ctx.GetVar("EIPId_01"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeEIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279DeleteULB15(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := ulbClient.NewDeleteULBRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "ULBId", ctx.GetVar("ULBId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return ulbClient.DeleteULB(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279PoweroffUHostInstance16(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := uhostClient.NewPoweroffUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("UHostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.PoweroffUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet279TerminateUHostInstance17(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("UHostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_283_test.go b/tests/set_283_test.go new file mode 100644 index 00000000..7436581e --- /dev/null +++ b/tests/set_283_test.go @@ -0,0 +1,610 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet283(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Region", "cn-bj2") + ctx.SetVar("Zone", "cn-bj2-05") + ctx.SetVar("DiskType", "DataDisk") + ctx.SetVar("Size", "1") + ctx.SetVar("UDataArkMode", "No") + ctx.SetVar("Name", "udisk_nofz") + ctx.SetVar("imageid", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + + testSet283DescribeUDiskPrice00(&ctx) + testSet283CheckUDiskAllowance01(&ctx) + testSet283CreateUDisk02(&ctx) + testSet283DescribeUDisk03(&ctx) + testSet283RenameUDisk04(&ctx) + testSet283DescribeUDisk05(&ctx) + testSet283DescribeImage06(&ctx) + testSet283CreateUHostInstance07(&ctx) + testSet283DescribeUHostInstance08(&ctx) + testSet283DescribeUHostLite09(&ctx) + testSet283AttachUDisk10(&ctx) + testSet283DescribeUDisk11(&ctx) + testSet283DetachUDisk12(&ctx) + testSet283DescribeUDisk13(&ctx) + testSet283DeleteUDisk14(&ctx) + testSet283PoweroffUHostInstance15(&ctx) + testSet283DescribeUHostInstance16(&ctx) + testSet283TerminateUHostInstance17(&ctx) +} + +func testSet283DescribeUDiskPrice00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDescribeUDiskPriceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "1")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", ctx.GetVar("UDataArkMode"))) + ctx.NoError(utest.SetReqValue(req, "DiskType", ctx.GetVar("DiskType"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDiskPrice(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283CheckUDiskAllowance01(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudiskClient.NewCheckUDiskAllowanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "Count", "1")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CheckUDiskAllowance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283CreateUDisk02(ctx *utest.TestContext) { + time.Sleep(time.Duration(1) * time.Second) + + req := udiskClient.NewCreateUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("Name"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "0")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", ctx.GetVar("UDataArkMode"))) + + ctx.NoError(utest.SetReqValue(req, "DiskType", ctx.GetVar("DiskType"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.CreateUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["udisk_nofz_id"] = ctx.Must(utest.GetValue(resp, "UDiskId.0")) +} + +func testSet283DescribeUDisk03(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeUDiskResponse", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + ctx.NewValidator("DataSet.0.Tag", "Default", "str_eq"), + }, + MaxRetries: 20, + RetryInterval: 3 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283RenameUDisk04(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewRenameUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "UDiskName", ctx.Must(utest.Concat("auto_", ctx.GetVar("Name"))))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.RenameUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283DescribeUDisk05(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + ctx.NoError(utest.SetReqValue(req, "Limit", "100")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Name", ctx.Must(utest.Concat("auto_", ctx.GetVar("Name"))), "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283DescribeImage06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewDescribeImageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageType", "Base")) + ctx.NoError(utest.SetReqValue(req, "OsType", "Linux")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeImage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeImageResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["imageid"] = ctx.Must(utest.GetValue(resp, "ImageSet.0.ImageId")) +} + +func testSet283CreateUHostInstance07(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("imageid"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=")) + + ctx.NoError(utest.SetReqValue(req, "CPU", "1")) + ctx.NoError(utest.SetReqValue(req, "Memory", "1024")) + ctx.NoError(utest.SetReqValue(req, "StorageType", "LocalDisk")) + ctx.NoError(utest.SetReqValue(req, "Name", "auto_uhost-同AZ")) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", "0")) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "0")) + ctx.NoError(utest.SetReqValue(req, "NetCapability", "Normal")) + + ctx.NoError(utest.SetReqValue(req, "BootDiskSpace", "20")) + ctx.NoError(utest.SetReqValue(req, "TimemachineFeature", "No")) + ctx.NoError(utest.SetReqValue(req, "HotplugFeature", "false")) + // ctx.NoError(utest.SetReqValue(req, "HostType", "N1")) + ctx.NoError(utest.SetReqValue(req, "UHostType", "Normal")) + ctx.NoError(utest.SetReqValue(req, "GPU", 0)) // TODO: check + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["uhost_id"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet283DescribeUHostInstance08(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("uhost_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeUHostInstanceResponse", "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("uhost_id"), "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283DescribeUHostLite09(ctx *utest.TestContext) { + time.Sleep(time.Duration(1) * time.Second) + + req := iuhostClient.NewDescribeUHostLiteRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + ctx.NoError(utest.SetReqValue(req, "Limit", "60")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DescribeUHostLite(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "0", "ne"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283AttachUDisk10(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := udiskClient.NewAttachUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("uhost_id"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.AttachUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283DescribeUDisk11(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + ctx.NoError(utest.SetReqValue(req, "Limit", "100")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "InUse", "str_eq"), + }, + MaxRetries: 20, + RetryInterval: 3 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283DetachUDisk12(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDetachUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("uhost_id"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DetachUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UDiskId", ctx.GetVar("udisk_nofz_id"), "str_eq"), + ctx.NewValidator("UHostId", ctx.GetVar("uhost_id"), "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283DescribeUDisk13(ctx *utest.TestContext) { + time.Sleep(time.Duration(120) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + ctx.NoError(utest.SetReqValue(req, "Limit", "100")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 50, + RetryInterval: 6 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283DeleteUDisk14(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDeleteUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DeleteUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283PoweroffUHostInstance15(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewPoweroffUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("uhost_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.PoweroffUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283DescribeUHostInstance16(ctx *utest.TestContext) { + time.Sleep(time.Duration(20) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("uhost_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet283TerminateUHostInstance17(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("uhost_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_286_test.go b/tests/set_286_test.go new file mode 100644 index 00000000..8526b96e --- /dev/null +++ b/tests/set_286_test.go @@ -0,0 +1,401 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet286(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Region", "cn-bj2") + ctx.SetVar("Zone", "cn-bj2-05") + ctx.SetVar("DiskType", "DataDisk") + ctx.SetVar("Size", "1") + ctx.SetVar("UDataArkMode", "No") + ctx.SetVar("Name", "auto_udisk_nofz") + + testSet286DescribeUDiskPrice00(&ctx) + testSet286CheckUDiskAllowance01(&ctx) + testSet286CreateUDisk02(&ctx) + testSet286DescribeUDisk03(&ctx) + testSet286CloneUDisk04(&ctx) + testSet286DescribeUDisk05(&ctx) + testSet286DescribeUDiskUpgradePrice06(&ctx) + testSet286ResizeUDisk07(&ctx) + testSet286DescribeUDisk08(&ctx) + testSet286DeleteUDisk09(&ctx) + testSet286DescribeUDisk10(&ctx) + testSet286DeleteUDisk11(&ctx) +} + +func testSet286DescribeUDiskPrice00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDescribeUDiskPriceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "1")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", ctx.GetVar("UDataArkMode"))) + ctx.NoError(utest.SetReqValue(req, "DiskType", ctx.GetVar("DiskType"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDiskPrice(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet286CheckUDiskAllowance01(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudiskClient.NewCheckUDiskAllowanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "Count", "1")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CheckUDiskAllowance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet286CreateUDisk02(ctx *utest.TestContext) { + time.Sleep(time.Duration(1) * time.Second) + + req := udiskClient.NewCreateUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("Name"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "0")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", ctx.GetVar("UDataArkMode"))) + ctx.NoError(utest.SetReqValue(req, "Tag", "test")) + ctx.NoError(utest.SetReqValue(req, "DiskType", ctx.GetVar("DiskType"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.CreateUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["udisk_nofz_id"] = ctx.Must(utest.GetValue(resp, "UDiskId.0")) +} + +func testSet286DescribeUDisk03(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeUDiskResponse", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + ctx.NewValidator("DataSet.0.Tag", "test", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet286CloneUDisk04(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := udiskClient.NewCloneUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Name", "clone_nofz")) + ctx.NoError(utest.SetReqValue(req, "SourceId", ctx.GetVar("udisk_nofz_id"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "0")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.CloneUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["clone_udisk_id_nofz"] = ctx.Must(utest.GetValue(resp, "UDiskId.0")) +} + +func testSet286DescribeUDisk05(ctx *utest.TestContext) { + time.Sleep(time.Duration(120) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("clone_udisk_id_nofz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 50, + RetryInterval: 3 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet286DescribeUDiskUpgradePrice06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDescribeUDiskUpgradePriceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.Must(utest.Calculate("+", ctx.GetVar("Size"), "1")))) + ctx.NoError(utest.SetReqValue(req, "SourceId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDiskUpgradePrice(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet286ResizeUDisk07(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := udiskClient.NewResizeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.Must(utest.Calculate("+", ctx.GetVar("Size"), "1")))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.ResizeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet286DescribeUDisk08(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Size", ctx.Must(utest.Calculate("+", ctx.GetVar("Size"), "1")), "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 2 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet286DeleteUDisk09(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDeleteUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DeleteUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet286DescribeUDisk10(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("clone_udisk_id_nofz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 20, + RetryInterval: 3 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet286DeleteUDisk11(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDeleteUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("clone_udisk_id_nofz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DeleteUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_289_test.go b/tests/set_289_test.go new file mode 100644 index 00000000..f914e717 --- /dev/null +++ b/tests/set_289_test.go @@ -0,0 +1,759 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet289(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Region", "cn-bj2") + ctx.SetVar("Zone", "cn-bj2-05") + ctx.SetVar("DiskType", "DataDisk") + ctx.SetVar("Size", "1") + ctx.SetVar("UDataArkMode", "No") + ctx.SetVar("Name", "auto_udisk_nofz") + + testSet289DescribeUDiskPrice00(&ctx) + testSet289CheckUDiskAllowance01(&ctx) + testSet289CreateUDisk02(&ctx) + testSet289DescribeUDisk03(&ctx) + testSet289CreateUDiskSnapshot04(&ctx) + testSet289DescribeUDisk05(&ctx) + testSet289DescribeSnapshot06(&ctx) + testSet289CreateUDiskSnapshot07(&ctx) + testSet289DescribeSnapshot08(&ctx) + testSet289CreateUDiskSnapshot09(&ctx) + testSet289DescribeSnapshot10(&ctx) + testSet289CreateUDiskSnapshot11(&ctx) + testSet289CloneUDiskSnapshot12(&ctx) + testSet289CloneUDiskSnapshot13(&ctx) + testSet289RestoreUHostDisk14(&ctx) + testSet289DescribeUDisk15(&ctx) + testSet289DeleteSnapshot16(&ctx) + testSet289DescribeSnapshot17(&ctx) + testSet289DeleteUDisk18(&ctx) + testSet289DescribeUDisk19(&ctx) + testSet289DeleteUDisk20(&ctx) + testSet289DescribeUDisk21(&ctx) + testSet289DeleteUDisk22(&ctx) +} + +func testSet289DescribeUDiskPrice00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDescribeUDiskPriceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "1")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", ctx.GetVar("UDataArkMode"))) + ctx.NoError(utest.SetReqValue(req, "DiskType", ctx.GetVar("DiskType"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDiskPrice(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289CheckUDiskAllowance01(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudiskClient.NewCheckUDiskAllowanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "Count", "1")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CheckUDiskAllowance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289CreateUDisk02(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := udiskClient.NewCreateUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("Name"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "0")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", ctx.GetVar("UDataArkMode"))) + + ctx.NoError(utest.SetReqValue(req, "DiskType", ctx.GetVar("DiskType"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.CreateUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["udisk_nofz_id"] = ctx.Must(utest.GetValue(resp, "UDiskId.0")) +} + +func testSet289DescribeUDisk03(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + ctx.NoError(utest.SetReqValue(req, "Limit", "100")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289CreateUDiskSnapshot04(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudiskClient.NewCreateUDiskSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "Name", "snapshot_01")) + + ctx.NoError(utest.SetReqValue(req, "Comment", "comment_01")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CreateUDiskSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["snapshot_id"] = ctx.Must(utest.GetValue(resp, "SnapshotId.0")) +} + +func testSet289DescribeUDisk05(ctx *utest.TestContext) { + time.Sleep(time.Duration(120) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.SnapshotLimit", "3", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + ctx.NewValidator("DataSet.0.SnapshotCount", "1", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289DescribeSnapshot06(ctx *utest.TestContext) { + time.Sleep(time.Duration(120) * time.Second) + + req := iuhostClient.NewDescribeSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "SnapshotIds", ctx.GetVar("snapshot_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DescribeSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSnapshotSet.0.DiskId", ctx.GetVar("udisk_nofz_id"), "str_eq"), // TODO: udisk nofz id + ctx.NewValidator("UHostSnapshotSet.0.State", "Normal", "str_eq"), + }, + MaxRetries: 50, + RetryInterval: 3 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289CreateUDiskSnapshot07(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudiskClient.NewCreateUDiskSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "Name", "snapshot_01")) + + ctx.NoError(utest.SetReqValue(req, "Comment", "comment_01")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CreateUDiskSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["snapshot_id"] = ctx.Must(utest.GetValue(resp, "SnapshotId.0")) +} + +func testSet289DescribeSnapshot08(ctx *utest.TestContext) { + time.Sleep(time.Duration(120) * time.Second) + + req := iuhostClient.NewDescribeSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "SnapshotIds", ctx.GetVar("snapshot_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DescribeSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSnapshotSet.0.DiskId", ctx.GetVar("udisk_nofz_id"), "str_eq"), + ctx.NewValidator("UHostSnapshotSet.0.State", "Normal", "str_eq"), + }, + MaxRetries: 6, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289CreateUDiskSnapshot09(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudiskClient.NewCreateUDiskSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "Name", "snapshot_01")) + + ctx.NoError(utest.SetReqValue(req, "Comment", "comment_01")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CreateUDiskSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["snapshot_id"] = ctx.Must(utest.GetValue(resp, "SnapshotId.0")) +} + +func testSet289DescribeSnapshot10(ctx *utest.TestContext) { + time.Sleep(time.Duration(120) * time.Second) + + req := iuhostClient.NewDescribeSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "SnapshotIds", ctx.GetVar("snapshot_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DescribeSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSnapshotSet.0.DiskId", ctx.GetVar("udisk_nofz_id"), "str_eq"), + ctx.NewValidator("UHostSnapshotSet.0.State", "Normal", "str_eq"), + }, + MaxRetries: 6, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289CreateUDiskSnapshot11(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := iudiskClient.NewCreateUDiskSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "Name", "snapshot_01")) + + ctx.NoError(utest.SetReqValue(req, "Comment", "comment_01")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CreateUDiskSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "16999", "gt"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289CloneUDiskSnapshot12(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudiskClient.NewCloneUDiskSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Name", "clone_from_kz_fz")) + ctx.NoError(utest.SetReqValue(req, "SourceId", ctx.GetVar("snapshot_id"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "0")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", "Yes")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CloneUDiskSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["udisk_id_fromkz_fz"] = ctx.Must(utest.GetValue(resp, "UDiskId.0")) +} + +func testSet289CloneUDiskSnapshot13(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := iudiskClient.NewCloneUDiskSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Name", "clone_from_kz_nofz")) + ctx.NoError(utest.SetReqValue(req, "SourceId", ctx.GetVar("snapshot_id"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "0")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", "No")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CloneUDiskSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["udisk_id_fromkz_nofz"] = ctx.Must(utest.GetValue(resp, "UDiskId.0")) +} + +func testSet289RestoreUHostDisk14(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iuhostClient.NewRestoreUHostDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + ctx.NoError(utest.SetReqValue(req, "SnapshotIds", ctx.GetVar("snapshot_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.RestoreUHostDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289DescribeUDisk15(ctx *utest.TestContext) { + time.Sleep(time.Duration(50) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 20, + RetryInterval: 3 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289DeleteSnapshot16(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iuhostClient.NewDeleteSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "SnapshotId", ctx.GetVar("snapshot_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DeleteSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("SnapshotId", ctx.GetVar("snapshot_id"), "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289DescribeSnapshot17(ctx *utest.TestContext) { + time.Sleep(time.Duration(1) * time.Second) + + req := iuhostClient.NewDescribeSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "SnapshotIds", ctx.GetVar("snapshot_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DescribeSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "0", "str_eq"), + ctx.NewValidator("PerDiskQuota", "3", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289DeleteUDisk18(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDeleteUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DeleteUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289DescribeUDisk19(ctx *utest.TestContext) { + time.Sleep(time.Duration(100) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_id_fromkz_nofz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Name", "clone_from_kz_nofz", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289DeleteUDisk20(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDeleteUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_id_fromkz_nofz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DeleteUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289DescribeUDisk21(ctx *utest.TestContext) { + time.Sleep(time.Duration(20) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_id_fromkz_fz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Name", "clone_from_kz_fz", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet289DeleteUDisk22(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDeleteUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_id_fromkz_fz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DeleteUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_293_test.go b/tests/set_293_test.go new file mode 100644 index 00000000..f5cdbee7 --- /dev/null +++ b/tests/set_293_test.go @@ -0,0 +1,748 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet293(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Region", "cn-bj2") + ctx.SetVar("Zone", "cn-bj2-05") + ctx.SetVar("DiskType", "DataDisk") + ctx.SetVar("Size", "1") + ctx.SetVar("UDataArkMode", "No") + ctx.SetVar("Name", "udisk_nofz") + + testSet293DescribeUDiskPrice00(&ctx) + testSet293CheckUDiskAllowance01(&ctx) + testSet293CreateUDisk02(&ctx) + testSet293DescribeUDisk03(&ctx) + testSet293SetUDiskUDataArkMode04(&ctx) + testSet293DescribeUDisk05(&ctx) + testSet293CreateUDiskSnapshot06(&ctx) + testSet293DescribeUDisk07(&ctx) + testSet293DescribeSnapshot08(&ctx) + testSet293CloneUDiskSnapshot09(&ctx) + testSet293DescribeUDisk10(&ctx) + testSet293CloneUDiskSnapshot11(&ctx) + testSet293DescribeUDisk12(&ctx) + testSet293RestoreUHostDisk13(&ctx) + testSet293DescribeUDisk14(&ctx) + testSet293DeleteSnapshot15(&ctx) + testSet293DescribeSnapshot16(&ctx) + testSet293DescribeUDisk17(&ctx) + testSet293DeleteUDisk18(&ctx) + testSet293DescribeUDisk19(&ctx) + testSet293DeleteUDisk20(&ctx) + testSet293DescribeUDisk21(&ctx) + testSet293DeleteUDisk22(&ctx) +} + +func testSet293DescribeUDiskPrice00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDescribeUDiskPriceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "1")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", ctx.GetVar("UDataArkMode"))) + ctx.NoError(utest.SetReqValue(req, "DiskType", ctx.GetVar("DiskType"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDiskPrice(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293CheckUDiskAllowance01(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudiskClient.NewCheckUDiskAllowanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "Count", "1")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CheckUDiskAllowance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293CreateUDisk02(ctx *utest.TestContext) { + time.Sleep(time.Duration(1) * time.Second) + + req := udiskClient.NewCreateUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.Must(utest.Concat("auto_", ctx.GetVar("Name"))))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "0")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", ctx.GetVar("UDataArkMode"))) + + ctx.NoError(utest.SetReqValue(req, "DiskType", ctx.GetVar("DiskType"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.CreateUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["udisk_nofz_id"] = ctx.Must(utest.GetValue(resp, "UDiskId.0")) +} + +func testSet293DescribeUDisk03(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293SetUDiskUDataArkMode04(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewSetUDiskUDataArkModeRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", "Yes")) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.SetUDiskUDataArkMode(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DescribeUDisk05(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.UDataArkMode", "Yes", "str_eq"), + }, + MaxRetries: 5, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293CreateUDiskSnapshot06(ctx *utest.TestContext) { + time.Sleep(time.Duration(300) * time.Second) + + req := iudiskClient.NewCreateUDiskSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + ctx.NoError(utest.SetReqValue(req, "Name", "snapshot_01_fz")) + + ctx.NoError(utest.SetReqValue(req, "Comment", "comment_01_fz")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CreateUDiskSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["snapshot_id"] = ctx.Must(utest.GetValue(resp, "SnapshotId.0")) +} + +func testSet293DescribeUDisk07(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.SnapshotLimit", "3", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + ctx.NewValidator("DataSet.0.SnapshotCount", "1", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DescribeSnapshot08(ctx *utest.TestContext) { + time.Sleep(time.Duration(20) * time.Second) + + req := iuhostClient.NewDescribeSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "SnapshotIds", ctx.GetVar("snapshot_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DescribeSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSnapshotSet.0.DiskId", ctx.GetVar("udisk_nofz_id"), "str_eq"), + ctx.NewValidator("UHostSnapshotSet.0.State", "Normal", "str_eq"), + }, + MaxRetries: 20, + RetryInterval: 3 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293CloneUDiskSnapshot09(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iudiskClient.NewCloneUDiskSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Name", "clone_from_kz_fz")) + ctx.NoError(utest.SetReqValue(req, "SourceId", ctx.GetVar("snapshot_id"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "0")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", "Yes")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CloneUDiskSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["udisk_id_fromkz_fz"] = ctx.Must(utest.GetValue(resp, "UDiskId.0")) +} + +func testSet293DescribeUDisk10(ctx *utest.TestContext) { + time.Sleep(time.Duration(120) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_id_fromkz_fz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Name", "clone_from_kz_fz", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 50, + RetryInterval: 6 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293CloneUDiskSnapshot11(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := iudiskClient.NewCloneUDiskSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "Name", "clone_from_kz_nofz")) + ctx.NoError(utest.SetReqValue(req, "SourceId", ctx.GetVar("snapshot_id"))) + ctx.NoError(utest.SetReqValue(req, "Size", ctx.GetVar("Size"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", "Month")) + ctx.NoError(utest.SetReqValue(req, "Quantity", "0")) + + ctx.NoError(utest.SetReqValue(req, "UDataArkMode", "No")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iudiskClient.CloneUDiskSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["udisk_id_fromkz_nofz"] = ctx.Must(utest.GetValue(resp, "UDiskId.0")) +} + +func testSet293DescribeUDisk12(ctx *utest.TestContext) { + time.Sleep(time.Duration(120) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_id_fromkz_nofz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Name", "clone_from_kz_nofz", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 50, + RetryInterval: 6 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293RestoreUHostDisk13(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := iuhostClient.NewRestoreUHostDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + ctx.NoError(utest.SetReqValue(req, "SnapshotIds", ctx.GetVar("snapshot_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.RestoreUHostDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DescribeUDisk14(ctx *utest.TestContext) { + time.Sleep(time.Duration(120) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Name", ctx.Must(utest.Concat("auto_", ctx.GetVar("Name"))), "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DeleteSnapshot15(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := iuhostClient.NewDeleteSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "SnapshotId", ctx.GetVar("snapshot_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DeleteSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("SnapshotId", ctx.GetVar("snapshot_id"), "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DescribeSnapshot16(ctx *utest.TestContext) { + time.Sleep(time.Duration(1) * time.Second) + + req := iuhostClient.NewDescribeSnapshotRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "SnapshotIds", ctx.GetVar("snapshot_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.DescribeSnapshot(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "0", "str_eq"), + ctx.NewValidator("PerDiskQuota", "3", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DescribeUDisk17(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 2 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DeleteUDisk18(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDeleteUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_nofz_id"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DeleteUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DescribeUDisk19(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_id_fromkz_nofz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 2 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DeleteUDisk20(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDeleteUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_id_fromkz_nofz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DeleteUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DescribeUDisk21(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDescribeUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_id_fromkz_fz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DescribeUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Status", "Available", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 2 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet293DeleteUDisk22(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := udiskClient.NewDeleteUDiskRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UDiskId", ctx.GetVar("udisk_id_fromkz_fz"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return udiskClient.DeleteUDisk(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 2 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_302_test.go b/tests/set_302_test.go new file mode 100644 index 00000000..327259d1 --- /dev/null +++ b/tests/set_302_test.go @@ -0,0 +1,515 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet302(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("tag", "tag_api_test") + ctx.SetVar("remark", "remark_api_test") + ctx.SetVar("fw_name_1", "fw_name_A_") + ctx.SetVar("Region", "cn-bj2") + ctx.SetVar("fw_rule_1_protocol", "TCP") + ctx.SetVar("fw_rule_1_port", "1111") + ctx.SetVar("fw_rule_1_srcip", "0.0.0.0/0") + ctx.SetVar("fw_rule_1_action", "ACCEPT") + ctx.SetVar("fw_rule_1_priority", "HIGH") + ctx.SetVar("Zone", "cn-bj2-05") + ctx.SetVar("uhost_name_1", "firewall_api_test") + ctx.SetVar("fw_rule_2_protocol", "UDP") + ctx.SetVar("fw_rule_2_port", "2222") + ctx.SetVar("fw_rule_2_srcip", "10.0.0.0/8") + ctx.SetVar("fw_rule_2_action", "DROP") + ctx.SetVar("fw_rule_2_priority", "LOW") + ctx.SetVar("fw_name_2", "fw_name_2_") + ctx.SetVar("tag_2", "tag_api_test_2") + ctx.SetVar("remark_2", "remark_api_test_2") + ctx.SetVar("Image_Id", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + ctx.SetVar("recommend_web", "recommend web") + + testSet302CreateUHostInstance00(&ctx) + testSet302CreateFirewall01(&ctx) + testSet302DescribeFirewall02(&ctx) + testSet302GrantFirewall03(&ctx) + testSet302DescribeFirewallResource04(&ctx) + testSet302UpdateFirewall05(&ctx) + testSet302UpdateFirewallAttribute06(&ctx) + testSet302DescribeFirewall07(&ctx) + testSet302DescribeFirewall08(&ctx) + testSet302GrantFirewall09(&ctx) + testSet302PoweroffUHostInstance10(&ctx) + testSet302TerminateUHostInstance11(&ctx) + testSet302DescribeFirewall12(&ctx) + testSet302DeleteFirewall13(&ctx) + testSet302DescribeFirewall14(&ctx) +} + +func testSet302CreateUHostInstance00(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("Image_Id"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", "dWNsb3VkLmNuMA==")) + + ctx.NoError(utest.SetReqValue(req, "CPU", "1")) + ctx.NoError(utest.SetReqValue(req, "Memory", "1024")) + + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("uhost_name_1"))) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", "0")) + + ctx.NoError(utest.SetReqValue(req, "Tag", ctx.GetVar("tag"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["uhost_id1"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet302CreateFirewall01(ctx *utest.TestContext) { + time.Sleep(time.Duration(180) * time.Second) + + req := unetClient.NewCreateFirewallRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.Must(utest.Concat(ctx.GetVar("fw_name_1"), ctx.GetVar("Zone"))))) + ctx.NoError(utest.SetReqValue(req, "Tag", ctx.GetVar("tag"))) + ctx.NoError(utest.SetReqValue(req, "Remark", ctx.GetVar("remark"))) + ctx.NoError(utest.SetReqValue(req, "Rule", ctx.Must(utest.ConcatWithVertical(ctx.GetVar("fw_rule_1_protocol"), ctx.GetVar("fw_rule_1_port"), ctx.GetVar("fw_rule_1_srcip"), ctx.GetVar("fw_rule_1_action"), ctx.GetVar("fw_rule_1_priority"))))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.CreateFirewall(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["fw_id1"] = ctx.Must(utest.GetValue(resp, "FWId")) +} + +func testSet302DescribeFirewall02(ctx *utest.TestContext) { + time.Sleep(time.Duration(3) * time.Second) + + req := unetClient.NewDescribeFirewallRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "FWId", ctx.GetVar("fw_id1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeFirewall(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.FWId", ctx.GetVar("fw_id1"), "str_eq"), + ctx.NewValidator("DataSet.0.Name", ctx.Must(utest.Concat(ctx.GetVar("fw_name_1"), ctx.GetVar("Zone"))), "str_eq"), + ctx.NewValidator("DataSet.0.Tag", ctx.GetVar("tag"), "str_eq"), + ctx.NewValidator("DataSet.0.Remark", ctx.GetVar("remark"), "str_eq"), + ctx.NewValidator("DataSet.0.ResourceCount", "0", "str_eq"), + ctx.NewValidator("DataSet.0.Type", "user defined", "str_eq"), + ctx.NewValidator("DataSet.0.Rule.0.ProtocolType", ctx.GetVar("fw_rule_1_protocol"), "str_eq"), + ctx.NewValidator("DataSet.0.Rule.0.DstPort", ctx.GetVar("fw_rule_1_port"), "str_eq"), + ctx.NewValidator("DataSet.0.Rule.0.SrcIP", ctx.GetVar("fw_rule_1_srcip"), "str_eq"), + ctx.NewValidator("DataSet.0.Rule.0.RuleAction", ctx.GetVar("fw_rule_1_action"), "str_eq"), + ctx.NewValidator("DataSet.0.Rule.0.Priority", ctx.GetVar("fw_rule_1_priority"), "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302GrantFirewall03(ctx *utest.TestContext) { + time.Sleep(time.Duration(3) * time.Second) + + req := unetClient.NewGrantFirewallRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "FWId", ctx.GetVar("fw_id1"))) + ctx.NoError(utest.SetReqValue(req, "ResourceType", "UHost")) + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("uhost_id1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.GrantFirewall(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302DescribeFirewallResource04(ctx *utest.TestContext) { + time.Sleep(time.Duration(3) * time.Second) + + req := unetClient.NewDescribeFirewallResourceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "FWId", ctx.GetVar("fw_id1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeFirewallResource(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("ResourceSet.0.Name", ctx.GetVar("uhost_name_1"), "str_eq"), + ctx.NewValidator("ResourceSet.0.ResourceType", "uhost", "str_eq"), + ctx.NewValidator("ResourceSet.0.ResourceID", ctx.GetVar("uhost_id1"), "str_eq"), + ctx.NewValidator("TotalCount", "1", "str_eq"), + ctx.NewValidator("ResourceSet.0.Tag", ctx.GetVar("tag"), "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302UpdateFirewall05(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewUpdateFirewallRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "FWId", ctx.GetVar("fw_id1"))) + ctx.NoError(utest.SetReqValue(req, "Rule", ctx.Must(utest.ConcatWithVertical(ctx.GetVar("fw_rule_2_protocol"), ctx.GetVar("fw_rule_2_port"), ctx.GetVar("fw_rule_2_srcip"), ctx.GetVar("fw_rule_2_action"), ctx.GetVar("fw_rule_2_priority"))))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.UpdateFirewall(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302UpdateFirewallAttribute06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewUpdateFirewallAttributeRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "FWId", ctx.GetVar("fw_id1"))) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.Must(utest.Concat(ctx.GetVar("fw_name_2"), ctx.GetVar("Zone"))))) + ctx.NoError(utest.SetReqValue(req, "Tag", ctx.GetVar("tag_2"))) + ctx.NoError(utest.SetReqValue(req, "Remark", ctx.GetVar("remark_2"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.UpdateFirewallAttribute(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302DescribeFirewall07(ctx *utest.TestContext) { + time.Sleep(time.Duration(3) * time.Second) + + req := unetClient.NewDescribeFirewallRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "FWId", ctx.GetVar("fw_id1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeFirewall(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.FWId", ctx.GetVar("fw_id1"), "str_eq"), + ctx.NewValidator("DataSet.0.Name", ctx.Must(utest.Concat(ctx.GetVar("fw_name_2"), ctx.GetVar("Zone"))), "str_eq"), + ctx.NewValidator("DataSet.0.Tag", ctx.GetVar("tag_2"), "str_eq"), + ctx.NewValidator("DataSet.0.Remark", ctx.GetVar("remark_2"), "str_eq"), + ctx.NewValidator("DataSet.0.ResourceCount", "1", "str_eq"), + ctx.NewValidator("DataSet.0.Type", "user defined", "str_eq"), + ctx.NewValidator("DataSet.0.Rule.0.ProtocolType", ctx.GetVar("fw_rule_2_protocol"), "str_eq"), + ctx.NewValidator("DataSet.0.Rule.0.DstPort", ctx.GetVar("fw_rule_2_port"), "str_eq"), + ctx.NewValidator("DataSet.0.Rule.0.SrcIP", ctx.GetVar("fw_rule_2_srcip"), "str_eq"), + ctx.NewValidator("DataSet.0.Rule.0.RuleAction", ctx.GetVar("fw_rule_2_action"), "str_eq"), + ctx.NewValidator("DataSet.0.Rule.0.Priority", ctx.GetVar("fw_rule_2_priority"), "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302DescribeFirewall08(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewDescribeFirewallRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "Limit", "20")) + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeFirewall(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["fw_dataset"] = ctx.Must(utest.GetValue(resp, "DataSet")) +} + +func testSet302GrantFirewall09(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewGrantFirewallRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "FWId", ctx.Must(utest.SearchValue(ctx.GetVar("fw_dataset"), "Type", ctx.GetVar("recommend_web"), "FWId")))) + ctx.NoError(utest.SetReqValue(req, "ResourceType", "UHost")) + ctx.NoError(utest.SetReqValue(req, "ResourceId", ctx.GetVar("uhost_id1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.GrantFirewall(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302PoweroffUHostInstance10(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := uhostClient.NewPoweroffUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("uhost_id1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.PoweroffUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 60 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302TerminateUHostInstance11(ctx *utest.TestContext) { + time.Sleep(time.Duration(90) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("uhost_id1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302DescribeFirewall12(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := unetClient.NewDescribeFirewallRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "FWId", ctx.GetVar("fw_id1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeFirewall(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.ResourceCount", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302DeleteFirewall13(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := unetClient.NewDeleteFirewallRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "FWId", ctx.GetVar("fw_id1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DeleteFirewall(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet302DescribeFirewall14(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewDescribeFirewallRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "Limit", "10")) + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeFirewall(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet", ctx.GetVar("fw_id1"), "object_not_contains"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_333_test.go b/tests/set_333_test.go new file mode 100644 index 00000000..f3bb95a8 --- /dev/null +++ b/tests/set_333_test.go @@ -0,0 +1,787 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet333(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Password", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=") + ctx.SetVar("ImageName", "ImageTest") + ctx.SetVar("TargetImageName", "ImageCopyTest") + ctx.SetVar("TargetRegion", "cn-sh2") + ctx.SetVar("TargetZone", "cn-sh2-02") + ctx.SetVar("myImage", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + + testSet333CreateUHostInstance00(&ctx) + testSet333DescribeUHostInstance01(&ctx) + testSet333StopUHostInstance02(&ctx) + testSet333DescribeUHostInstance03(&ctx) + testSet333CreateCustomImage04(&ctx) + testSet333DescribeImage05(&ctx) + testSet333CreateUHostInstance06(&ctx) + testSet333DescribeUHostInstance07(&ctx) + testSet333GetProjectList08(&ctx) + testSet333CopyCustomImage09(&ctx) + testSet333GetImageCopyProgress10(&ctx) + testSet333DescribeImage11(&ctx) + testSet333CreateUHostInstance12(&ctx) + testSet333DescribeUHostInstance13(&ctx) + testSet333TerminateCustomImage14(&ctx) + testSet333StopUHostInstance15(&ctx) + testSet333StopUHostInstance16(&ctx) + testSet333DescribeUHostInstance17(&ctx) + testSet333TerminateUHostInstance18(&ctx) + testSet333TerminateUHostInstance19(&ctx) + testSet333TerminateCustomImage20(&ctx) + testSet333StopUHostInstance21(&ctx) + testSet333DescribeUHostInstance22(&ctx) + testSet333TerminateUHostInstance23(&ctx) +} + +func testSet333CreateUHostInstance00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("myImage"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", ctx.GetVar("Password"))) + + ctx.NoError(utest.SetReqValue(req, "CPU", "1")) + ctx.NoError(utest.SetReqValue(req, "Memory", "1024")) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", "0")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["hostId"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet333DescribeUHostInstance01(ctx *utest.TestContext) { + time.Sleep(time.Duration(400) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeUHostInstanceResponse", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + }, + MaxRetries: 60, + RetryInterval: 60 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333StopUHostInstance02(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewStopUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StopUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "StopUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333DescribeUHostInstance03(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeUHostInstanceResponse", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333CreateCustomImage04(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewCreateCustomImageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + ctx.NoError(utest.SetReqValue(req, "ImageName", ctx.GetVar("ImageName"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateCustomImage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["newImageId"] = ctx.Must(utest.GetValue(resp, "ImageId")) +} + +func testSet333DescribeImage05(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := uhostClient.NewDescribeImageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("newImageId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeImage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeImageResponse", "str_eq"), + ctx.NewValidator("ImageSet.0.State", "Available", "str_eq"), + ctx.NewValidator("ImageSet.0.ImageId", ctx.GetVar("newImageId"), "str_eq"), + }, + MaxRetries: 100, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333CreateUHostInstance06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("newImageId"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", ctx.GetVar("Password"))) + + ctx.NoError(utest.SetReqValue(req, "CPU", "1")) + ctx.NoError(utest.SetReqValue(req, "Memory", "1024")) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", "0")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["hostId2"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet333DescribeUHostInstance07(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId2"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeUHostInstanceResponse", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + }, + MaxRetries: 100, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333GetProjectList08(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uaccountClient.NewGetProjectListRequest() + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uaccountClient.GetProjectList(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "GetProjectListResponse", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["TargetProjectID"] = ctx.Must(utest.GetValue(resp, "ProjectSet.0.ProjectId")) +} + +func testSet333CopyCustomImage09(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewCopyCustomImageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + + ctx.NoError(utest.SetReqValue(req, "SourceImageId", ctx.GetVar("newImageId"))) + ctx.NoError(utest.SetReqValue(req, "TargetRegion", ctx.GetVar("TargetRegion"))) + ctx.NoError(utest.SetReqValue(req, "TargetProjectId", ctx.GetVar("TargetProjectID"))) + ctx.NoError(utest.SetReqValue(req, "TargetImageName", ctx.GetVar("TargetImageName"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CopyCustomImage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["cpImageId"] = ctx.Must(utest.GetValue(resp, "TargetImageId")) +} + +func testSet333GetImageCopyProgress10(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := iuhostClient.NewGetImageCopyProgressRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("TargetRegion"))) + + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("cpImageId"))) + ctx.NoError(utest.SetReqValue(req, "ProjectId", ctx.GetVar("TargetProjectID"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return iuhostClient.GetImageCopyProgress(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("ProgressInfo", "100.00", "float_eq"), + }, + MaxRetries: 60, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333DescribeImage11(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewDescribeImageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("TargetRegion"))) + + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("cpImageId"))) + + ctx.NoError(utest.SetReqValue(req, "ProjectId", ctx.GetVar("TargetProjectID"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeImage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeImageResponse", "str_eq"), + ctx.NewValidator("ImageSet.0.State", "Available", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333CreateUHostInstance12(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("TargetRegion"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("TargetZone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("cpImageId"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", ctx.GetVar("Password"))) + + ctx.NoError(utest.SetReqValue(req, "CPU", "1")) + ctx.NoError(utest.SetReqValue(req, "Memory", "1024")) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", "0")) + + ctx.NoError(utest.SetReqValue(req, "ProjectId", ctx.GetVar("TargetProjectID"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["hostId_new"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet333DescribeUHostInstance13(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("TargetRegion"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("TargetZone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId_new"))) + + ctx.NoError(utest.SetReqValue(req, "ProjectId", ctx.GetVar("TargetProjectID"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeUHostInstanceResponse", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + }, + MaxRetries: 60, + RetryInterval: 60 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333TerminateCustomImage14(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewTerminateCustomImageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("newImageId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateCustomImage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333StopUHostInstance15(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewStopUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StopUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333StopUHostInstance16(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewStopUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId2"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StopUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333DescribeUHostInstance17(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "UHostIds", []string{ctx.GetVar("hostId").(string), ctx.GetVar("hostId2").(string)})) // TODO: check + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeUHostInstanceResponse", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + ctx.NewValidator("UHostSet.1.State", "Stopped", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333TerminateUHostInstance18(ctx *utest.TestContext) { + time.Sleep(time.Duration(5) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333TerminateUHostInstance19(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId2"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333TerminateCustomImage20(ctx *utest.TestContext) { + time.Sleep(time.Duration(100) * time.Second) + + req := uhostClient.NewTerminateCustomImageRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("TargetRegion"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("TargetZone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("cpImageId"))) + ctx.NoError(utest.SetReqValue(req, "ProjectId", ctx.GetVar("TargetProjectID"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateCustomImage(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333StopUHostInstance21(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewStopUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("TargetRegion"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("TargetZone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId_new"))) + ctx.NoError(utest.SetReqValue(req, "ProjectId", ctx.GetVar("TargetProjectID"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StopUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333DescribeUHostInstance22(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("TargetRegion"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("TargetZone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId_new"))) + + ctx.NoError(utest.SetReqValue(req, "ProjectId", ctx.GetVar("TargetProjectID"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "DescribeUHostInstanceResponse", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet333TerminateUHostInstance23(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("TargetRegion"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("TargetZone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId_new"))) + ctx.NoError(utest.SetReqValue(req, "ProjectId", ctx.GetVar("TargetProjectID"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_448_test.go b/tests/set_448_test.go new file mode 100644 index 00000000..9fcf2bfa --- /dev/null +++ b/tests/set_448_test.go @@ -0,0 +1,409 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet448(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Password", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=") + ctx.SetVar("CreateBootDisk", "20") + ctx.SetVar("ChargeType", "Month") + ctx.SetVar("CreateCPU", "1") + ctx.SetVar("CreateMem", "1024") + ctx.SetVar("CreateDiskspace", "0") + ctx.SetVar("UpgradeDiskSpace", "10") + ctx.SetVar("NewPassword", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=") + ctx.SetVar("Name", "uhost-basic-api-N2-Normal-LocalDisk-1") + ctx.SetVar("ImageID", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + ctx.SetVar("UpgradeBootDisk", "40") + ctx.SetVar("UpgradeCPU", "2") + + testSet448CreateUHostInstance00(&ctx) + testSet448DescribeUHostInstance01(&ctx) + testSet448RebootUHostInstance02(&ctx) + testSet448DescribeUHostInstance03(&ctx) + testSet448StopUHostInstance04(&ctx) + testSet448DescribeUHostInstance05(&ctx) + testSet448ResizeUHostInstance06(&ctx) + testSet448DescribeUHostInstance07(&ctx) + testSet448PoweroffUHostInstance08(&ctx) + testSet448DescribeUHostInstance09(&ctx) + testSet448TerminateUHostInstance10(&ctx) +} + +func testSet448CreateUHostInstance00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("ImageID"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", ctx.GetVar("Password"))) + + ctx.NoError(utest.SetReqValue(req, "CPU", ctx.GetVar("CreateCPU"))) + ctx.NoError(utest.SetReqValue(req, "Memory", ctx.GetVar("CreateMem"))) + ctx.NoError(utest.SetReqValue(req, "StorageType", "LocalDisk")) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("Name"))) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", ctx.GetVar("CreateDiskspace"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", ctx.GetVar("ChargeType"))) + ctx.NoError(utest.SetReqValue(req, "Quantity", "1")) + ctx.NoError(utest.SetReqValue(req, "NetCapability", "Normal")) + ctx.NoError(utest.SetReqValue(req, "Tag", "Default")) + + ctx.NoError(utest.SetReqValue(req, "BootDiskSpace", ctx.GetVar("CreateBootDisk"))) + ctx.NoError(utest.SetReqValue(req, "TimemachineFeature", "No")) + ctx.NoError(utest.SetReqValue(req, "HotplugFeature", "false")) + ctx.NoError(utest.SetReqValue(req, "HostType", "N2")) + + ctx.NoError(utest.SetReqValue(req, "GPU", 0)) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["hostId"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet448DescribeUHostInstance01(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("CreateCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("Name"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("CreateDiskspace"), "str_eq"), + ctx.NewValidator("UHostSet.0.HostType", "N2", "str_eq"), + ctx.NewValidator("UHostSet.0.UHostType", "Normal", "str_eq"), + ctx.NewValidator("UHostSet.0.StorageType", "LocalDisk", "str_eq"), + // ctx.NewValidator("UHostSet.0.BasicImageId", ctx.GetVar("ImageID"), "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + }, + MaxRetries: 200, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet448RebootUHostInstance02(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewRebootUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.RebootUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 5, + RetryInterval: 60 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet448DescribeUHostInstance03(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("CreateCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("Name"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("CreateDiskspace"), "str_eq"), + ctx.NewValidator("UHostSet.0.HostType", "N2", "str_eq"), + ctx.NewValidator("UHostSet.0.UHostType", "Normal", "str_eq"), + ctx.NewValidator("UHostSet.0.StorageType", "LocalDisk", "str_eq"), + // ctx.NewValidator("UHostSet.0.BasicImageId", ctx.GetVar("ImageID"), "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet448StopUHostInstance04(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewStopUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StopUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 5, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet448DescribeUHostInstance05(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet448ResizeUHostInstance06(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewResizeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + ctx.NoError(utest.SetReqValue(req, "CPU", ctx.GetVar("UpgradeCPU"))) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", ctx.GetVar("UpgradeDiskSpace"))) + + ctx.NoError(utest.SetReqValue(req, "BootDiskSpace", ctx.GetVar("UpgradeBootDisk"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.ResizeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 5, + RetryInterval: 45 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet448DescribeUHostInstance07(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("UpgradeDiskSpace"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("Name"), "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("UpgradeCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.HostType", "N2", "str_eq"), + ctx.NewValidator("UHostSet.0.UHostType", "Normal", "str_eq"), + ctx.NewValidator("UHostSet.0.StorageType", "LocalDisk", "str_eq"), + // ctx.NewValidator("UHostSet.0.BasicImageId", ctx.GetVar("ImageID"), "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + ctx.NewValidator("UHostSet.0.DiskSet.0.Size", ctx.GetVar("UpgradeBootDisk"), "str_eq"), + }, + MaxRetries: 60, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet448PoweroffUHostInstance08(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewPoweroffUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.PoweroffUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 5, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet448DescribeUHostInstance09(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet448TerminateUHostInstance10(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_449_test.go b/tests/set_449_test.go new file mode 100644 index 00000000..ed5f2def --- /dev/null +++ b/tests/set_449_test.go @@ -0,0 +1,344 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet449(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Password", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=") + ctx.SetVar("CreateBootDisk", "20") + ctx.SetVar("ChargeType", "Month") + ctx.SetVar("CreateCPU", "1") + ctx.SetVar("CreateMem", "1024") + ctx.SetVar("CreateDiskspace", "0") + ctx.SetVar("NewPassword", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=") + ctx.SetVar("Name", "uhost-basic-api") + ctx.SetVar("ImageID", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + + testSet449CreateUHostInstance00(&ctx) + testSet449DescribeUHostInstance01(&ctx) + testSet449StopUHostInstance02(&ctx) + testSet449DescribeUHostInstance03(&ctx) + testSet449ReinstallUHostInstance04(&ctx) + testSet449DescribeUHostInstance05(&ctx) + testSet449PoweroffUHostInstance06(&ctx) + testSet449DescribeUHostInstance07(&ctx) + testSet449TerminateUHostInstance08(&ctx) +} + +func testSet449CreateUHostInstance00(ctx *utest.TestContext) { + time.Sleep(time.Duration(20) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("ImageID"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", ctx.GetVar("Password"))) + + ctx.NoError(utest.SetReqValue(req, "CPU", ctx.GetVar("CreateCPU"))) + ctx.NoError(utest.SetReqValue(req, "Memory", ctx.GetVar("CreateMem"))) + ctx.NoError(utest.SetReqValue(req, "StorageType", "LocalDisk")) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("Name"))) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", ctx.GetVar("CreateDiskspace"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", ctx.GetVar("ChargeType"))) + ctx.NoError(utest.SetReqValue(req, "Quantity", "1")) + ctx.NoError(utest.SetReqValue(req, "NetCapability", "Normal")) + ctx.NoError(utest.SetReqValue(req, "Tag", "Default")) + + ctx.NoError(utest.SetReqValue(req, "BootDiskSpace", ctx.GetVar("CreateBootDisk"))) + ctx.NoError(utest.SetReqValue(req, "TimemachineFeature", "No")) + ctx.NoError(utest.SetReqValue(req, "HotplugFeature", "false")) + ctx.NoError(utest.SetReqValue(req, "HostType", "N2")) + + ctx.NoError(utest.SetReqValue(req, "GPU", 0)) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["hostId"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet449DescribeUHostInstance01(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + // ctx.NewValidator("UHostSet.0.BasicImageId", ctx.GetVar("ImageID"), "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("CreateCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("Name"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("CreateDiskspace"), "str_eq"), + ctx.NewValidator("UHostSet.0.HostType", "N2", "str_eq"), + ctx.NewValidator("UHostSet.0.UHostType", "Normal", "str_eq"), + ctx.NewValidator("UHostSet.0.StorageType", "LocalDisk", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + }, + MaxRetries: 200, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet449StopUHostInstance02(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewStopUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StopUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "StopUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 5, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet449DescribeUHostInstance03(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + // ctx.NewValidator("UHostSet.0.BasicImageId", ctx.GetVar("ImageID"), "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("CreateCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("Name"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("CreateDiskspace"), "str_eq"), + ctx.NewValidator("UHostSet.0.HostType", "N2", "str_eq"), + ctx.NewValidator("UHostSet.0.UHostType", "Normal", "str_eq"), + ctx.NewValidator("UHostSet.0.StorageType", "LocalDisk", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet449ReinstallUHostInstance04(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewReinstallUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + ctx.NoError(utest.SetReqValue(req, "Password", ctx.GetVar("NewPassword"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("ImageID"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.ReinstallUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 5, + RetryInterval: 60 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet449DescribeUHostInstance05(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + // ctx.NewValidator("UHostSet.0.BasicImageId", ctx.GetVar("ImageID"), "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("CreateDiskspace"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("Name"), "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("CreateCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.HostType", "N2", "str_eq"), + ctx.NewValidator("UHostSet.0.UHostType", "Normal", "str_eq"), + ctx.NewValidator("UHostSet.0.StorageType", "LocalDisk", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + }, + MaxRetries: 200, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet449PoweroffUHostInstance06(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewPoweroffUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.PoweroffUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 60 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet449DescribeUHostInstance07(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet449TerminateUHostInstance08(ctx *utest.TestContext) { + time.Sleep(time.Duration(60) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_471_test.go b/tests/set_471_test.go new file mode 100644 index 00000000..c54158b2 --- /dev/null +++ b/tests/set_471_test.go @@ -0,0 +1,323 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet471(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Password", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=") + ctx.SetVar("CreateBootDisk", "20") + ctx.SetVar("ChargeType", "Month") + ctx.SetVar("CreateCPU", "1") + ctx.SetVar("CreateMem", "1024") + ctx.SetVar("CreateDiskspace", "0") + ctx.SetVar("NewPassword", "Z3VhbmxpeXVhbm1pbWExMjMhQCM=") + ctx.SetVar("Name", "uhost-basic-api-ResetPassword") + ctx.SetVar("ImageID", ctx.Must(utest.GetImageResource(ctx.GetVar("Region"), ctx.GetVar("Zone")))) + + testSet471CreateUHostInstance00(&ctx) + testSet471DescribeUHostInstance01(&ctx) + testSet471StopUHostInstance02(&ctx) + testSet471DescribeUHostInstance03(&ctx) + testSet471ResetUHostInstancePassword04(&ctx) + testSet471DescribeUHostInstance05(&ctx) + testSet471PoweroffUHostInstance06(&ctx) + testSet471DescribeUHostInstance07(&ctx) + testSet471TerminateUHostInstance08(&ctx) +} + +func testSet471CreateUHostInstance00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uhostClient.NewCreateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "ImageId", ctx.GetVar("ImageID"))) + ctx.NoError(utest.SetReqValue(req, "LoginMode", "Password")) + ctx.NoError(utest.SetReqValue(req, "Password", ctx.GetVar("Password"))) + + ctx.NoError(utest.SetReqValue(req, "CPU", ctx.GetVar("CreateCPU"))) + ctx.NoError(utest.SetReqValue(req, "Memory", ctx.GetVar("CreateMem"))) + ctx.NoError(utest.SetReqValue(req, "StorageType", "LocalDisk")) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("Name"))) + + ctx.NoError(utest.SetReqValue(req, "DiskSpace", ctx.GetVar("CreateDiskspace"))) + + ctx.NoError(utest.SetReqValue(req, "ChargeType", ctx.GetVar("ChargeType"))) + ctx.NoError(utest.SetReqValue(req, "Quantity", "1")) + ctx.NoError(utest.SetReqValue(req, "NetCapability", "Normal")) + ctx.NoError(utest.SetReqValue(req, "Tag", "Default")) + + ctx.NoError(utest.SetReqValue(req, "BootDiskSpace", ctx.GetVar("CreateBootDisk"))) + ctx.NoError(utest.SetReqValue(req, "TimemachineFeature", "No")) + ctx.NoError(utest.SetReqValue(req, "HotplugFeature", "false")) + + ctx.NoError(utest.SetReqValue(req, "GPU", 0)) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.CreateUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["hostId"] = ctx.Must(utest.GetValue(resp, "UHostIds.0")) +} + +func testSet471DescribeUHostInstance01(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.CPU", ctx.GetVar("CreateCPU"), "str_eq"), + ctx.NewValidator("UHostSet.0.Memory", ctx.GetVar("CreateMem"), "str_eq"), + ctx.NewValidator("UHostSet.0.UHostId", ctx.GetVar("hostId"), "str_eq"), + ctx.NewValidator("UHostSet.0.Name", ctx.GetVar("Name"), "str_eq"), + ctx.NewValidator("UHostSet.0.TotalDiskSpace", ctx.GetVar("CreateDiskspace"), "str_eq"), + ctx.NewValidator("UHostSet.0.StorageType", "LocalDisk", "str_eq"), + // ctx.NewValidator("UHostSet.0.BasicImageId", ctx.GetVar("ImageID"), "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Running", "str_eq"), + }, + MaxRetries: 120, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet471StopUHostInstance02(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewStopUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.StopUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "StopUHostInstanceResponse", "str_eq"), + }, + MaxRetries: 5, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet471DescribeUHostInstance03(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + ctx.NewValidator("UHostSet.0.BootDiskState", "Normal", "str_eq"), + }, + MaxRetries: 100, + RetryInterval: 60 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet471ResetUHostInstancePassword04(ctx *utest.TestContext) { + time.Sleep(time.Duration(20) * time.Second) + + req := uhostClient.NewResetUHostInstancePasswordRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + ctx.NoError(utest.SetReqValue(req, "Password", ctx.GetVar("NewPassword"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.ResetUHostInstancePassword(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 10, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet471DescribeUHostInstance05(ctx *utest.TestContext) { + time.Sleep(time.Duration(10) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 60, + RetryInterval: 30 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet471PoweroffUHostInstance06(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewPoweroffUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.PoweroffUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 60 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet471DescribeUHostInstance07(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewDescribeUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostIds", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.DescribeUHostInstance(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("UHostSet.0.State", "Stopped", "str_eq"), + }, + MaxRetries: 30, + RetryInterval: 10 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet471TerminateUHostInstance08(ctx *utest.TestContext) { + time.Sleep(time.Duration(30) * time.Second) + + req := uhostClient.NewTerminateUHostInstanceRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "UHostId", ctx.GetVar("hostId"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uhostClient.TerminateUHostInstance(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/set_687_test.go b/tests/set_687_test.go new file mode 100644 index 00000000..4b1a9a47 --- /dev/null +++ b/tests/set_687_test.go @@ -0,0 +1,716 @@ +package tests + +import ( + "testing" + "time" + + "github.com/ucloud/ucloud-sdk-go/internal/utest" +) + +func TestSet687(t *testing.T) { + ctx := utest.NewTestContext() + ctx.T = t + ctx.Vars = map[string]interface{}{} + + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("Zone", "cn-sh2-02") + + ctx.SetVar("Zone", "cn-sh2-02") + ctx.SetVar("Region", "cn-sh2") + ctx.SetVar("VPC_name_1", "VPC_api_test_1") + ctx.SetVar("remark", "remark_api_test") + ctx.SetVar("tag", "tag_api_test") + ctx.SetVar("Subnet_name_1_1", "subnet_1_1") + ctx.SetVar("subnet_netmask", "24") + + testSet687GetProjectList00(&ctx) + testSet687CreateVPC01(&ctx) + testSet687CreateSubnet02(&ctx) + testSet687DescribeSubnet03(&ctx) + testSet687CreateVPC04(&ctx) + testSet687CreateSubnet05(&ctx) + testSet687CreateSubnet06(&ctx) + testSet687DescribeSubnet07(&ctx) + testSet687AllocateVIP08(&ctx) + testSet687DescribeVIP09(&ctx) + testSet687DescribeSubnetResource10(&ctx) + testSet687ReleaseVIP11(&ctx) + testSet687DeleteSubnet12(&ctx) + testSet687DeleteSubnet13(&ctx) + testSet687DeleteSubnet14(&ctx) + testSet687AddVPCNetwork15(&ctx) + testSet687DescribeVPC16(&ctx) + testSet687CreateVPCIntercom17(&ctx) + testSet687DescribeVPCIntercom18(&ctx) + testSet687DeleteVPCIntercom19(&ctx) + testSet687DeleteVPC20(&ctx) + testSet687DeleteVPC21(&ctx) +} + +func testSet687GetProjectList00(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := uaccountClient.NewGetProjectListRequest() + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return uaccountClient.GetProjectList(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("Action", "GetProjectListResponse", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["project_list"] = ctx.Must(utest.GetValue(resp, "ProjectSet")) +} + +func testSet687CreateVPC01(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := vpcClient.NewCreateVPCRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Name", ctx.GetVar("VPC_name_1"))) + ctx.NoError(utest.SetReqValue(req, "Network", "172.16.16.0/20")) + ctx.NoError(utest.SetReqValue(req, "Tag", ctx.GetVar("tag"))) + ctx.NoError(utest.SetReqValue(req, "Remark", ctx.GetVar("remark"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.CreateVPC(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["VPCId_1"] = ctx.Must(utest.GetValue(resp, "VPCId")) +} + +func testSet687CreateSubnet02(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := vpcClient.NewCreateSubnetRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_1"))) + ctx.NoError(utest.SetReqValue(req, "Subnet", "172.16.17.0")) + ctx.NoError(utest.SetReqValue(req, "Netmask", ctx.GetVar("subnet_netmask"))) + ctx.NoError(utest.SetReqValue(req, "SubnetName", ctx.GetVar("Subnet_name_1_1"))) + ctx.NoError(utest.SetReqValue(req, "Tag", ctx.GetVar("tag"))) + ctx.NoError(utest.SetReqValue(req, "Remark", ctx.GetVar("remark"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.CreateSubnet(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["SubnetId_1_1"] = ctx.Must(utest.GetValue(resp, "SubnetId")) +} + +func testSet687DescribeSubnet03(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := vpcClient.NewDescribeSubnetRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "SubnetId", ctx.GetVar("SubnetId_1_1"))) + + ctx.NoError(utest.SetReqValue(req, "Offset", "1")) + ctx.NoError(utest.SetReqValue(req, "Limit", "1")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DescribeSubnet(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687CreateVPC04(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := vpcClient.NewCreateVPCRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "Name", "vpc_2")) + ctx.NoError(utest.SetReqValue(req, "Network", "192.168.16.0/20")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.CreateVPC(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["VPCId_2"] = ctx.Must(utest.GetValue(resp, "VPCId")) +} + +func testSet687CreateSubnet05(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := vpcClient.NewCreateSubnetRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_2"))) + ctx.NoError(utest.SetReqValue(req, "Subnet", "192.168.17.0")) + ctx.NoError(utest.SetReqValue(req, "Netmask", ctx.GetVar("subnet_netmask"))) + ctx.NoError(utest.SetReqValue(req, "SubnetName", "Subnet_2_1")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.CreateSubnet(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["SubnetId_2_1"] = ctx.Must(utest.GetValue(resp, "SubnetId")) +} + +func testSet687CreateSubnet06(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := vpcClient.NewCreateSubnetRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_2"))) + ctx.NoError(utest.SetReqValue(req, "Subnet", "192.168.18.0")) + ctx.NoError(utest.SetReqValue(req, "Netmask", ctx.GetVar("subnet_netmask"))) + ctx.NoError(utest.SetReqValue(req, "SubnetName", "Subnet_2_2")) + + ctx.NoError(utest.SetReqValue(req, "Remark", "remark_2_2")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.CreateSubnet(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["SubnetId_2_2"] = ctx.Must(utest.GetValue(resp, "SubnetId")) +} + +func testSet687DescribeSubnet07(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := vpcClient.NewDescribeSubnetRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "SubnetId", ctx.GetVar("SubnetId_1_1"))) + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DescribeSubnet(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.VPCId", ctx.GetVar("VPCId_1"), "str_eq"), + ctx.NewValidator("DataSet.0.VPCName", ctx.GetVar("VPC_name_1"), "str_eq"), + ctx.NewValidator("DataSet.0.SubnetId", ctx.GetVar("SubnetId_1_1"), "str_eq"), + ctx.NewValidator("DataSet.0.SubnetName", ctx.GetVar("Subnet_name_1_1"), "str_eq"), + ctx.NewValidator("DataSet.0.Tag", ctx.GetVar("tag"), "str_eq"), + ctx.NewValidator("DataSet.0.Remark", ctx.GetVar("remark"), "str_eq"), + ctx.NewValidator("DataSet.0.SubnetType", "2", "str_eq"), + ctx.NewValidator("DataSet.0.Netmask", "24", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687AllocateVIP08(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewAllocateVIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_1"))) + ctx.NoError(utest.SetReqValue(req, "SubnetId", ctx.GetVar("SubnetId_1_1"))) + + ctx.NoError(utest.SetReqValue(req, "Name", "vip_api_auto")) + + ctx.NoError(utest.SetReqValue(req, "Remark", "vip_tag1")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.AllocateVIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["VIPId_1"] = ctx.Must(utest.GetValue(resp, "VIPSet.0.VIPId")) +} + +func testSet687DescribeVIP09(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := unetClient.NewDescribeVIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_1"))) + ctx.NoError(utest.SetReqValue(req, "SubnetId", ctx.GetVar("SubnetId_1_1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.DescribeVIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("VIPSet.0.VPCId", ctx.GetVar("VPCId_1"), "str_eq"), + ctx.NewValidator("VIPSet.0.VIPId", ctx.GetVar("VIPId_1"), "str_eq"), + ctx.NewValidator("VIPSet.0.SubnetId", ctx.GetVar("SubnetId_1_1"), "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + + ctx.Vars["VIP_ip_1"] = ctx.Must(utest.GetValue(resp, "DataSet.0")) +} + +func testSet687DescribeSubnetResource10(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := vpcClient.NewDescribeSubnetResourceRequest() + + ctx.NoError(utest.SetReqValue(req, "SubnetId", ctx.GetVar("SubnetId_1_1"))) + + ctx.NoError(utest.SetReqValue(req, "Offset", "0")) + ctx.NoError(utest.SetReqValue(req, "Limit", "20")) + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DescribeSubnetResource(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("TotalCount", "1", "str_eq"), + ctx.NewValidator("DataSet.0.ResourceId", ctx.GetVar("VIPId_1"), "str_eq"), + ctx.NewValidator("DataSet.0.IP", ctx.GetVar("VIP_ip_1"), "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687ReleaseVIP11(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := unetClient.NewReleaseVIPRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "Zone", ctx.GetVar("Zone"))) + ctx.NoError(utest.SetReqValue(req, "VIPId", ctx.GetVar("VIPId_1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return unetClient.ReleaseVIP(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687DeleteSubnet12(ctx *utest.TestContext) { + time.Sleep(time.Duration(1) * time.Second) + + req := vpcClient.NewDeleteSubnetRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "SubnetId", ctx.GetVar("SubnetId_1_1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DeleteSubnet(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687DeleteSubnet13(ctx *utest.TestContext) { + time.Sleep(time.Duration(1) * time.Second) + + req := vpcClient.NewDeleteSubnetRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "SubnetId", ctx.GetVar("SubnetId_2_1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DeleteSubnet(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687DeleteSubnet14(ctx *utest.TestContext) { + time.Sleep(time.Duration(1) * time.Second) + + req := vpcClient.NewDeleteSubnetRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "SubnetId", ctx.GetVar("SubnetId_2_2"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DeleteSubnet(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687AddVPCNetwork15(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := vpcClient.NewAddVPCNetworkRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_1"))) + ctx.NoError(utest.SetReqValue(req, "Network", "10.100.96.0/20")) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.AddVPCNetwork(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687DescribeVPC16(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := vpcClient.NewDescribeVPCRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "VPCIds", ctx.GetVar("VPCId_1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DescribeVPC(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687CreateVPCIntercom17(ctx *utest.TestContext) { + time.Sleep(time.Duration(0) * time.Second) + + req := vpcClient.NewCreateVPCIntercomRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_1"))) + ctx.NoError(utest.SetReqValue(req, "DstRegion", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "DstProjectId", ctx.Must(utest.SearchValue(ctx.GetVar("project_list"), "IsDefault", "true", "ProjectId")))) + ctx.NoError(utest.SetReqValue(req, "DstVPCId", ctx.GetVar("VPCId_2"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.CreateVPCIntercom(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687DescribeVPCIntercom18(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := vpcClient.NewDescribeVPCIntercomRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DescribeVPCIntercom(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + ctx.NewValidator("DataSet.0.VPCId", ctx.GetVar("VPCId_2"), "str_eq"), + ctx.NewValidator("DataSet.0.DstRegion", ctx.GetVar("Region"), "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687DeleteVPCIntercom19(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := vpcClient.NewDeleteVPCIntercomRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_1"))) + + ctx.NoError(utest.SetReqValue(req, "DstRegion", ctx.GetVar("Region"))) + ctx.NoError(utest.SetReqValue(req, "DstProjectId", ctx.Must(utest.SearchValue(ctx.GetVar("project_list"), "IsDefault", "true", "ProjectId")))) + ctx.NoError(utest.SetReqValue(req, "DstVPCId", ctx.GetVar("VPCId_2"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DeleteVPCIntercom(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 0, + RetryInterval: 0 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687DeleteVPC20(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := vpcClient.NewDeleteVPCRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_1"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DeleteVPC(req) + }, + Validators: []utest.TestValidator{ + ctx.NewValidator("RetCode", "0", "str_eq"), + }, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} + +func testSet687DeleteVPC21(ctx *utest.TestContext) { + time.Sleep(time.Duration(2) * time.Second) + + req := vpcClient.NewDeleteVPCRequest() + + ctx.NoError(utest.SetReqValue(req, "Region", ctx.GetVar("Region"))) + + ctx.NoError(utest.SetReqValue(req, "VPCId", ctx.GetVar("VPCId_2"))) + + testCase := utest.TestCase{ + Invoker: func() (interface{}, error) { + return vpcClient.DeleteVPC(req) + }, + Validators: []utest.TestValidator{}, + MaxRetries: 3, + RetryInterval: 1 * time.Second, + T: ctx.T, + } + + resp, err := testCase.Run() + if resp == nil || err != nil { + ctx.T.Fatal(err) + } + +} diff --git a/tests/setup_fixture.go b/tests/setup_fixture.go new file mode 100644 index 00000000..927a3bcc --- /dev/null +++ b/tests/setup_fixture.go @@ -0,0 +1,79 @@ +package tests + +import ( + "os" + "testing" + + "github.com/ucloud/ucloud-sdk-go/ucloud" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" + "github.com/ucloud/ucloud-sdk-go/ucloud/log" + + iudataark "github.com/ucloud/ucloud-sdk-go/internal/services/udataark" + iudisk "github.com/ucloud/ucloud-sdk-go/internal/services/udisk" + iuhost "github.com/ucloud/ucloud-sdk-go/internal/services/uhost" + iulb "github.com/ucloud/ucloud-sdk-go/internal/services/ulb" + iumon "github.com/ucloud/ucloud-sdk-go/internal/services/umon" + iunet "github.com/ucloud/ucloud-sdk-go/internal/services/unet" + + "github.com/ucloud/ucloud-sdk-go/services/pathx" + "github.com/ucloud/ucloud-sdk-go/services/uaccount" + "github.com/ucloud/ucloud-sdk-go/services/udisk" + "github.com/ucloud/ucloud-sdk-go/services/uhost" + "github.com/ucloud/ucloud-sdk-go/services/ulb" + "github.com/ucloud/ucloud-sdk-go/services/unet" + "github.com/ucloud/ucloud-sdk-go/services/vpc" +) + +var client *ucloud.Client +var uhostClient *uhost.UHostClient +var unetClient *unet.UNetClient +var ulbClient *ulb.ULBClient +var vpcClient *vpc.VPCClient +var uaccountClient *uaccount.UAccountClient +var pathxClient *pathx.PathXClient +var udiskClient *udisk.UDiskClient + +var iuhostClient *iuhost.UHostClient +var iunetClient *iunet.UNetClient +var iulbClient *iulb.ULBClient +var iudiskClient *iudisk.UDiskClient +var iumonClient *iumon.UMonClient +var iudataarkClient *iudataark.UDataArkClient + +func TestMain(m *testing.M) { + testSetup() + exitCode := m.Run() + testTeardown() + os.Exit(exitCode) +} + +func testSetup() { + cfg := ucloud.NewConfig() + cfg.LogLevel = log.DebugLevel + cfg.Region = os.Getenv("UCLOUD_REGION") + cfg.ProjectId = os.Getenv("UCLOUD_PROJECT_ID") + + credential := auth.NewCredential() + credential.PrivateKey = os.Getenv("UCLOUD_PRIVATE_KEY") + credential.PublicKey = os.Getenv("UCLOUD_PUBLIC_KEY") + + client = ucloud.NewClient(&cfg, &credential) + uhostClient = uhost.NewClient(&cfg, &credential) + unetClient = unet.NewClient(&cfg, &credential) + ulbClient = ulb.NewClient(&cfg, &credential) + vpcClient = vpc.NewClient(&cfg, &credential) + uaccountClient = uaccount.NewClient(&cfg, &credential) + pathxClient = pathx.NewClient(&cfg, &credential) + udiskClient = udisk.NewClient(&cfg, &credential) + + iudataarkClient = iudataark.NewClient(&cfg, &credential) + iudiskClient = iudisk.NewClient(&cfg, &credential) + iuhostClient = iuhost.NewClient(&cfg, &credential) + iulbClient = iulb.NewClient(&cfg, &credential) + iumonClient = iumon.NewClient(&cfg, &credential) + iunetClient = iunet.NewClient(&cfg, &credential) + + log.Info("setup test fixtures ...") +} + +func testTeardown() {} diff --git a/ucloud/auth/credential.go b/ucloud/auth/credential.go new file mode 100644 index 00000000..5d924e68 --- /dev/null +++ b/ucloud/auth/credential.go @@ -0,0 +1,52 @@ +package auth + +import ( + "crypto/sha1" + "encoding/hex" + "io" + "net/url" + "sort" + "strings" +) + +type Credential struct { + PublicKey string + PrivateKey string +} + +// NewCredential will return credential config with default values +func NewCredential() Credential { + return Credential{} +} + +// CreateSign will encode query string to credential signature. +func (c *Credential) CreateSign(query string) string { + // replace "=" "&" + str := strings.Replace(query, "&", "", -1) + str = strings.Replace(str, "=", "", -1) + + // crypto by SHA1 + strUnescaped, _ := url.QueryUnescape(str) + h := sha1.New() + s := strUnescaped + c.PrivateKey + io.WriteString(h, s) + bs := h.Sum(nil) + result := hex.EncodeToString(bs) + + return result +} + +// BuildCredentialedQuery will build query string with signature query param. +func (c *Credential) BuildCredentialedQuery(query map[string]string) string { + var queryList []string + for k, v := range query { + queryList = append(queryList, k+"="+url.QueryEscape(v)) + } + queryList = append(queryList, "PublicKey="+url.QueryEscape(c.PublicKey)) + sort.Strings(queryList) + queryString := strings.Join(queryList, "&") + + sign := c.CreateSign(queryString) + queryString = queryString + "&Signature=" + sign + return queryString +} diff --git a/ucloud/auth/credential_test.go b/ucloud/auth/credential_test.go new file mode 100644 index 00000000..c335cea3 --- /dev/null +++ b/ucloud/auth/credential_test.go @@ -0,0 +1,54 @@ +package auth + +import ( + "strings" + "testing" +) + +func TestCredential_CreateSign(t *testing.T) { + type fields struct { + PublicKey string + PrivateKey string + } + type args struct { + query string + } + tests := []struct { + name string + fields fields + args args + want string + }{ + { + "standard", + fields{"ucloudsomeone@example.com1296235120854146120", "46f09bb9fab4f12dfc160dae12273d5332b5debe"}, + args{testCredential_CreateSign_query00}, + "4f9ef5df2abab2c6fccd1e9515cb7e2df8c6bb65", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := &Credential{ + PublicKey: tt.fields.PublicKey, + PrivateKey: tt.fields.PrivateKey, + } + if got := c.CreateSign(tt.args.query); got != tt.want { + t.Errorf("Credential.CreateSign() = %v, want %v", got, tt.want) + } + }) + } +} + +var testCredential_CreateSign_query00 string = strings.Join(strings.Split(`Action=CreateUHostInstance +&CPU=2 +&ChargeType=Month +&DiskSpace=10 +&ImageId=f43736e1-65a5-4bea-ad2e-8a46e18883c2 +&LoginMode=Password +&Memory=2048 +&Name=Host01 +&Password=VUNsb3VkLmNu +&PublicKey=ucloudsomeone%40example.com1296235120854146120 +&Quantity=1 +&Region=cn-bj2 +&Zone=cn-bj2-04`, "\n"), "") diff --git a/ucloud/auth/credentials.go b/ucloud/auth/credentials.go deleted file mode 100644 index bcb1fca6..00000000 --- a/ucloud/auth/credentials.go +++ /dev/null @@ -1,38 +0,0 @@ -package auth - -import ( - "errors" - "os" -) - -var ( - ErrPublicKeyIDNotFound = errors.New("UCLOUD_PUBLIC_KEY not found in environment") - ErrPrivateKeyNotFound = errors.New("UCLOUD_PRIVATE_KEY not found in environment") -) - -type KeyPair struct { - // UCloud account public key - PublicKey string - - // UCloud account private key - PrivateKey string -} - -func LoadKeyPairFromEnv() (KeyPair, error) { - - publicKey := os.Getenv("UCLOUD_PUBLIC_KEY") - privateKey := os.Getenv("UCLOUD_PRIVATE_KEY") - - if publicKey == "" { - return KeyPair{}, ErrPublicKeyIDNotFound - } - - if privateKey == "" { - return KeyPair{}, ErrPrivateKeyNotFound - } - - return KeyPair{ - PublicKey: publicKey, - PrivateKey: privateKey, - }, nil -} diff --git a/ucloud/auth/credentials_test.go b/ucloud/auth/credentials_test.go deleted file mode 100644 index ebbe6cdd..00000000 --- a/ucloud/auth/credentials_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package auth - -import ( - "os" - "testing" -) - -func TestCredentialNotFound(t *testing.T) { - os.Clearenv() - - _, err := LoadKeyPairFromEnv() - if err == nil { - t.Errorf("expected: not found, actual: found") - } -} diff --git a/ucloud/auth/signature.go b/ucloud/auth/signature.go deleted file mode 100644 index b2573841..00000000 --- a/ucloud/auth/signature.go +++ /dev/null @@ -1,24 +0,0 @@ -package auth - -import ( - "crypto/sha1" - "errors" - "fmt" -) - -//GenerateSignature generate signature for request string for ucloud request api. -func GenerateSignature(requestString, privateKey string) (string, error) { - - if len(requestString) < 1 { - return "", errors.New("Wrong request parameters.") - } - - if len(privateKey) < 1 { - return "", errors.New("Wrong private key.") - } - - h := sha1.New() - h.Write([]byte(requestString + privateKey)) - - return fmt.Sprintf("%x", h.Sum(nil)), nil -} diff --git a/ucloud/auth/signature_test.go b/ucloud/auth/signature_test.go deleted file mode 100644 index f365793e..00000000 --- a/ucloud/auth/signature_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package auth - -import ( - "testing" -) - -func TestGenerateSignature(t *testing.T) { - var ( - requestParams = "ActionCreateUHostInstanceCPU2ChargeTypeMonthDiskSpace10ImageIdf43736e1-65a5-4bea-ad2e-8a46e18883c2LoginModePasswordMemory2048NameHost01PasswordVUNsb3VkLmNuPublicKeyucloudsomeone@example.com1296235120854146120Quantity1Regioncn-north-01" - privateKey = "46f09bb9fab4f12dfc160dae12273d5332b5debe" - signature = "64e0fe58642b75db052d50fd7380f79e6a0211bd" - ) - - sig, err := GenerateSignature(requestParams, privateKey) - - if err != nil { - t.Fatal("GenrateSignature failed") - } - - if sig != signature { - t.Fatalf("Expected %s, got %s", signature, sig) - } - - requestParams = "" - sig, err = GenerateSignature(requestParams, privateKey) - - if err == nil { - t.Fatal("GenrateSignature failed") - } -} diff --git a/ucloud/client.go b/ucloud/client.go new file mode 100644 index 00000000..cb42a629 --- /dev/null +++ b/ucloud/client.go @@ -0,0 +1,80 @@ +package ucloud + +import ( + "time" + + "github.com/ucloud/ucloud-sdk-go/private/protocol/http" + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" + "github.com/ucloud/ucloud-sdk-go/ucloud/log" + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// Client 客户端 +type Client struct { + credential *auth.Credential + config *Config + httpClient *http.HttpClient + + responseHandlers []ReponseHandler + httpResponseHandlers []HttpReponseHandler +} + +// NewClient will create an client of ucloud sdk +func NewClient(config *Config, credential *auth.Credential) *Client { + client := Client{ + credential: credential, + config: config, + } + + client.responseHandlers = append(client.responseHandlers, defaultResponseHandlers...) + client.httpResponseHandlers = append(client.httpResponseHandlers, defaultHttpResponseHandlers...) + log.Init(config.LogLevel) + return &client +} + +// GetCredential will return the creadential config of client. +func (c *Client) GetCredential() *auth.Credential { + return c.credential +} + +// GetConfig will return the config of client. +func (c *Client) GetConfig() *Config { + return c.config +} + +// InvokeAction will do an action request from a request struct and set response value into res struct pointer +func (c *Client) InvokeAction(action string, req request.Common, resp response.Common) error { + req.SetAction(action) + req.SetRequestTime(time.Now()) + + httpReq, err := c.buildHTTPRequest(req) + if err != nil { + return err + } + + httpClient := http.NewHttpClient() + httpResp, err := httpClient.Send(httpReq) + if err != nil { + return err + } + + // use response middleware to handle http response + // such as convert some http status to error + for _, handler := range c.httpResponseHandlers { + httpResp, err = handler(c, httpReq, httpResp, err) + } + + err = c.UnmarshalHTTPReponse(httpResp, resp) + if err != nil { + return err + } + + // use response middle to build and convert response when response has been created. + // such as retry, report traceback, print log and etc. + for _, handler := range c.responseHandlers { + resp, err = handler(c, req, resp, err) + } + + return err +} diff --git a/ucloud/client_test.go b/ucloud/client_test.go new file mode 100644 index 00000000..20dce4b7 --- /dev/null +++ b/ucloud/client_test.go @@ -0,0 +1,141 @@ +package ucloud + +import ( + "net/http" + "os" + "testing" + "time" + + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" + + "github.com/ucloud/ucloud-sdk-go/ucloud/auth" + uerr "github.com/ucloud/ucloud-sdk-go/ucloud/error" + "github.com/ucloud/ucloud-sdk-go/ucloud/log" + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +var client *Client + +func TestMain(m *testing.M) { + testSetup() + exitCode := m.Run() + testTeardown() + os.Exit(exitCode) +} + +func testSetup() { + cfg := NewConfig() + // cfg.BaseUrl = "https://api-mock.pre.ucloudadmin.com/?_user=yufei.li%40ucloud.cn" + cfg.BaseUrl = "https://api.ucloud.cn" + cfg.Region = "cn-bj2" + cfg.ProjectId = os.Getenv("UCLOUD_PROJECT_ID") + cfg.LogLevel = log.DebugLevel + + credential := auth.NewCredential() + credential.PrivateKey = os.Getenv("UCLOUD_PRIVATE_KEY") + credential.PublicKey = os.Getenv("UCLOUD_PUBLIC_KEY") + + log.Infof("config: %#v, credential: %#v", cfg, credential) + client = NewClient(&cfg, &credential) +} + +func testTeardown() {} + +type MockRequest struct { + request.CommonBase +} + +type MockResponse struct { + response.CommonBase + + TotalCount int + UHostSet []map[string]interface{} +} + +func TestCommonInvokeAction(t *testing.T) { + req := &MockRequest{} + resp := &MockResponse{} + + err := client.InvokeAction("DescribeUHostInstance", client.SetupRequest(req), resp) + assert.Nil(t, err) + assert.Condition(t, func() bool { return resp.TotalCount >= 0 }) +} + +func TestCommonInvokeActionNotFound(t *testing.T) { + req := &MockRequest{} + resp := &MockResponse{} + err := client.InvokeAction("TestApi", client.SetupRequest(req), resp) + assert.NotNil(t, err) + uErr, ok := err.(uerr.Error) + assert.True(t, ok) + assert.Equal(t, 161, uErr.Code()) + assert.Contains(t, uErr.Message(), "not found") +} + +func Test_errorHandler(t *testing.T) { + req := &MockRequest{} + resp := &MockResponse{} + + steps := []struct { + name string + step func() error + }{ + { + name: "unexcepted error", + step: func() error { + _, err := errorHandler(client, req, resp, errors.New("unexcepted error")) + if uErr, ok := err.(uerr.ClientError); !ok || uErr.Name() != uerr.ErrSendRequest { + return errors.New("unexcepted error should be convert to unknown client error") + } + return nil + }, + }, + { + name: "http status error", + step: func() error { + _, err := errorHandler(client, req, resp, uerr.NewServerStatusError(404, "404 NotFound")) + if uErr, ok := err.(uerr.ServerError); !ok || uErr.StatusCode() != 404 { + return errors.New("http status error should be convert to status server error") + } + return nil + }, + }, + { + name: "timeout error", + step: func() error { + httpClient := &http.Client{Timeout: time.Duration(1)} + httpReq, err := http.NewRequest("GET", "https://httpbin.org/delay/2", nil) + if err != nil { + return err + } + _, err = httpClient.Do(httpReq) + _, err = errorHandler(client, req, resp, err) + if uErr, ok := err.(uerr.ClientError); !ok || uErr.Name() != uerr.ErrNetwork { + return errors.New("timeout error should be convert to network client error") + } + return nil + }, + }, + { + name: "bussiness error", + step: func() error { + resp := &response.CommonBase{Message: "Missing Action", RetCode: 160} + _, err := errorHandler(client, req, resp, nil) + if uErr, ok := err.(uerr.ServerError); !ok || uErr.Code() != 160 { + return errors.New("ucloud error should be raised for non-zero retCode") + } + return nil + }, + }, + } + for _, step := range steps { + t.Run(step.name, func(t *testing.T) { + err := step.step() + if err != nil { + t.Errorf("errorHandler() error %s", err) + } + }) + } +} diff --git a/ucloud/config.go b/ucloud/config.go index e44c9ab7..d5e8bf85 100644 --- a/ucloud/config.go +++ b/ucloud/config.go @@ -1,127 +1,53 @@ package ucloud import ( - "os" "time" - "github.com/ucloud/ucloud-sdk-go/ucloud/auth" + "github.com/ucloud/ucloud-sdk-go/ucloud/log" ) -const ( - DefaultRetries = -1 - APIVersion string = "v2" - APIBaseURL string = "https://api.ucloud.cn/" -) - -var DefaultCredential, _ = auth.LoadKeyPairFromEnv() - -var DefaultConfig = NewConfig(). - WithCredentials(&DefaultCredential). - WithRegion(os.Getenv("UCLOUD_REGION")). - WithMaxRetries(DefaultRetries). - WithProjectID(""). - WithSleepDelay(time.Sleep) - -// A Config provides service configuration for service clients. By default, -// all clients will use the {defaults.DefaultConfig} structure. -// TODO: max retries and timeout should be added type Config struct { - Credentials *auth.KeyPair - - Region string - - MaxRetries int - - ProjectID string - - SleepDelay func(time.Duration) - - HTTPHeader map[string]string -} - -// NewConfig returns a new Config pointer that can be chained with builder methods to -// set multiple configuration values inline without using pointers. -// -// svc := uhost.New(ucloud.NewConfig().WithRegion("cn-bj-2").WithMaxRetries(10)) -// -func NewConfig() *Config { - return &Config{} -} - -// WithCredentials sets a config Credentials value returning a Config pointer -// for chaining. -func (c *Config) WithCredentials(creds *auth.KeyPair) *Config { - c.Credentials = creds - return c -} - -// WithRegion sets a config Region value returning a Config pointer for -// chaining. -func (c *Config) WithRegion(region string) *Config { - c.Region = region - return c -} - -// WithMaxRetries sets a config MaxRetries value returning a Config pointer -// for chaining. -func (c *Config) WithMaxRetries(max int) *Config { - c.MaxRetries = max - return c -} - -// WithProjectID sets a config ProjectID value returning a Config pointer -// for chaining -func (c *Config) WithProjectID(projectID string) *Config { - c.ProjectID = projectID - return c -} - -// WithSleepDelay overrides the function used to sleep while waiting for the -// next retry. Defaults to time.Sleep. -func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config { - c.SleepDelay = fn - return c -} - -// Merge returns a new Config with the other Config's attribute values merged into -// this Config. If the other Config's attribute is nil it will not be merged into -// the new Config to be returned. -func (c Config) Merge(other *Config) *Config { - if other == nil { - return &c - } - - dst := c - - if other.Credentials != nil { - dst.Credentials = other.Credentials - } - - if other.Region != "" { - dst.Region = other.Region - } - - if other.SleepDelay != nil { - dst.SleepDelay = other.SleepDelay + // Region is the region of backend service + // See also ... + Region string `default:""` + + // ProjectId is the unique identify of project, used for organize resources, + // Most of resources should belong to a project. + // Sub-Account must have an project id. + // See also ... + ProjectId string `default:""` + + // BaseUrl is the url of backend api + // See also ... + BaseUrl string `default:"https://api.ucloud.cn"` + + // UserAgent is an attribute for sdk client, used for distinguish who is using sdk. + // See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent + // It will be appended to the end of sdk user-agent. + // eg. "Terraform/0.10.1" -> "GO/1.9.1 GO-SDK/0.1.0 Terraform/0.10.1" + // NOTE: it will conflict with the User-Agent of HTTPHeaders + UserAgent string `default:""` + + // Timeout is timeout for every request. + Timeout time.Duration `default:"30s"` + + // MaxRetries is the number of max retry times. + // Set MaxRetries more than 0 to enable auto-retry for network and service availability problem + // if auto-retry is enabled, it will enable default retry policy using exponential backoff. + MaxRetries int `default:"0"` + + // LogLevel is equal to logrus level, + // if logLevel not be set, use INFO level as default. + LogLevel log.Level `default:"log.InfoLevel"` +} + +// NewConfig will return a new client config with default options. +func NewConfig() Config { + cfg := Config{ + BaseUrl: "https://api.ucloud.cn", + Timeout: 30 * time.Second, + MaxRetries: 0, + LogLevel: log.ErrorLevel, } - - if other.MaxRetries != -1 { - dst.MaxRetries = other.MaxRetries - } - - if len(other.ProjectID) != 0 { - dst.ProjectID = other.ProjectID - } - - if len(other.HTTPHeader) != 0 { - dst.HTTPHeader = other.HTTPHeader - } - - return &dst -} - -// Copy will return a shallow copy of the Config object. -func (c Config) Copy() *Config { - dst := c - return &dst + return cfg } diff --git a/ucloud/error/client_error.go b/ucloud/error/client_error.go new file mode 100644 index 00000000..f6f31bc1 --- /dev/null +++ b/ucloud/error/client_error.go @@ -0,0 +1,81 @@ +package uerr + +import ( + "fmt" + "net" +) + +var ( + // ErrInvalidRequest is the error for invalid request took from user + ErrInvalidRequest = "client.InvalidRequestError" + + // ErrSendRequest is the error for sending request + ErrSendRequest = "client.SendRequestError" + + // ErrNetwork is the error for any network error caused by client or server network environment + // ErrNetwork can be caused by net errors of golang + // ErrNetwork is retryable + ErrNetwork = "client.NetworkError" + + // ErrUnexcepted is the error for any unexcepted error + ErrUnexcepted = "client.UnexceptedError" +) + +// ClientError is the ucloud common errorfor server response +type ClientError struct { + err error + name string + retryable bool +} + +func (e ClientError) Error() string { + return fmt.Sprintf("sdk:\n[%s] %s", e.name, e.err.Error()) +} + +// NewClientError will return a new instance of ClientError +func NewClientError(name string, err error) ClientError { + return ClientError{ + name: name, + err: err, + retryable: false, + } +} + +// Name will return error name +func (e ClientError) Name() string { + return e.name +} + +// Code will return server code +func (e ClientError) Code() int { + return -1 +} + +// HTTPStatusCode will return http status code +func (e ClientError) StatusCode() int { + return 0 +} + +// Message will return message +func (e ClientError) Message() string { + return e.err.Error() +} + +// OriginError will return the origin error that caused by +func (e ClientError) OriginError() error { + return e.err +} + +// Retryable will return if the error is retryable +func (e ClientError) Retryable() bool { + return e.name == ErrNetwork || e.retryable +} + +// IsNetworkError will check if the error raise from network problem +func IsNetworkError(err error) bool { + if err == nil { + return false + } + _, isNetError := err.(net.Error) + return isNetError +} diff --git a/ucloud/error/error.go b/ucloud/error/error.go new file mode 100644 index 00000000..9810c3dc --- /dev/null +++ b/ucloud/error/error.go @@ -0,0 +1,58 @@ +package uerr + +// Error is the ucloud sdk error +type Error interface { + error + + // name, should be client.xxx or server.xxx + Name() string + + // retcode for server api error, retcode > 0 will cause an error + Code() int + + // http status code, code >= 400 will case an error + StatusCode() int + + // message for server api error + Message() string + + // the origin error that sdk error caused from + OriginError() error + + // if the error is retryable + Retryable() bool +} + +// NewRetryableError will wrap any error as a retryable error +func NewRetryableError(err error) Error { + if e, ok := err.(ClientError); ok { + e.retryable = true + return e + } + + if e, ok := err.(ServerError); ok { + e.retryable = true + return e + } + + e := NewClientError(ErrUnexcepted, err) + e.retryable = true + return e +} + +// NewNonRetryableError will wrap any error as a non-retryable error +func NewNonRetryableError(err error) Error { + if e, ok := err.(ClientError); ok { + e.retryable = false + return e + } + + if e, ok := err.(ServerError); ok { + e.retryable = false + return e + } + + e := NewClientError(ErrUnexcepted, err) + e.retryable = false + return e +} diff --git a/ucloud/error/error_test.go b/ucloud/error/error_test.go new file mode 100644 index 00000000..f932c007 --- /dev/null +++ b/ucloud/error/error_test.go @@ -0,0 +1,64 @@ +package uerr + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestClientError(t *testing.T) { + originErr := errors.New("o") + err := NewClientError(ErrUnexcepted, originErr) + + assert.Equal(t, err.Name(), ErrUnexcepted) + assert.Equal(t, err.Code(), -1) + assert.Equal(t, err.OriginError(), originErr) + assert.Equal(t, err.Retryable(), false) + assert.Equal(t, err.StatusCode(), 0) +} + +func TestServerError(t *testing.T) { + err := NewServerCodeError(160, "o") + + assert.Equal(t, err.Name(), ErrRetCode) + assert.Equal(t, err.Code(), 160) + assert.Error(t, err.OriginError()) + assert.Equal(t, err.Retryable(), false) + assert.Equal(t, err.StatusCode(), 200) + + err = NewServerStatusError(400, "o") + + assert.Equal(t, err.Name(), ErrHTTPStatus) + assert.Equal(t, err.Code(), -1) + assert.Error(t, err.OriginError()) + assert.Equal(t, err.Retryable(), false) + assert.Equal(t, err.StatusCode(), 400) +} + +func TestRetryableError(t *testing.T) { + err := NewRetryableError(errors.New("o")) + + assert.Equal(t, err.Name(), ErrUnexcepted) + assert.Equal(t, err.Code(), -1) + assert.Error(t, err.OriginError()) + assert.Equal(t, err.Retryable(), true) + assert.Equal(t, err.StatusCode(), 0) + + err = NewRetryableError(NewServerCodeError(160, "o")) + assert.Equal(t, err.Retryable(), true) + + err = NewRetryableError(NewServerStatusError(400, "o")) + assert.Equal(t, err.Retryable(), true) + + err = NewServerStatusError(400, "o") + assert.Equal(t, err.Retryable(), false) + + err = NewServerStatusError(429, "o") + assert.Equal(t, err.Retryable(), true) +} + +func TestNonRetryableError(t *testing.T) { + err := NewNonRetryableError(NewRetryableError(errors.New("o"))) + assert.Equal(t, err.Retryable(), false) +} diff --git a/ucloud/error/server_error.go b/ucloud/error/server_error.go new file mode 100644 index 00000000..14b2b946 --- /dev/null +++ b/ucloud/error/server_error.go @@ -0,0 +1,100 @@ +package uerr + +import ( + "fmt" + + "github.com/pkg/errors" +) + +var ( + ErrHTTPStatus = "server.HTTPStatusError" + ErrRetCode = "server.RetCodeError" +) + +// ServerError is the ucloud common error for server response +type ServerError struct { + err error + name string + statusCode int + retCode int + message string + retryable bool +} + +func (e ServerError) Error() string { + if e.retCode > 0 { + return fmt.Sprintf("api:\n[%s] %v %s", e.name, e.retCode, e.message) + } + return fmt.Sprintf("api:\n[%s] %s", e.name, e.message) +} + +// NewServerStatusError will return a new instance of NewServerStatusError +func NewServerStatusError(statusCode int, message string) ServerError { + return ServerError{ + retCode: -1, + statusCode: statusCode, + message: message, + name: ErrHTTPStatus, + err: errors.Errorf("%s", message), + retryable: false, + } +} + +// NewServerCodeError will return a new instance of NewServerStatusError +func NewServerCodeError(retCode int, message string) ServerError { + return ServerError{ + retCode: retCode, + statusCode: 200, + message: message, + name: ErrRetCode, + err: errors.Errorf("%s", message), + retryable: retCode >= 2000, + } +} + +// Name will return error name +func (e ServerError) Name() string { + return e.name +} + +// Code will return server code +func (e ServerError) Code() int { + return e.retCode +} + +// HTTPStatusCode will return http status code +func (e ServerError) StatusCode() int { + return e.statusCode +} + +// Message will return message +func (e ServerError) Message() string { + return e.message +} + +// OriginError will return the origin error that caused by +func (e ServerError) OriginError() error { + return e.err +} + +// Retryable will return if the error is retryable +func (e ServerError) Retryable() bool { + return isIn(e.statusCode, []int{429, 502, 503, 504}) || e.retryable +} + +func isIn(i int, avaliables []int) bool { + for _, v := range avaliables { + if i == v { + return true + } + } + return false +} + +// IsCodeError will check if the error is the retuen code error +func IsCodeError(err error) bool { + if e, ok := err.(Error); ok && e.Name() == ErrRetCode { + return true + } + return false +} diff --git a/ucloud/handlers.go b/ucloud/handlers.go new file mode 100644 index 00000000..501d59d8 --- /dev/null +++ b/ucloud/handlers.go @@ -0,0 +1,105 @@ +package ucloud + +import ( + "math/rand" + "time" + + "github.com/ucloud/ucloud-sdk-go/private/protocol/http" + uerr "github.com/ucloud/ucloud-sdk-go/ucloud/error" + "github.com/ucloud/ucloud-sdk-go/ucloud/log" + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" +) + +// ReponseHandler receive response and write data into this response memory area +type ReponseHandler func(c *Client, req request.Common, resp response.Common, err error) (response.Common, error) + +// HttpReponseHandler receive http response and return a new http response +type HttpReponseHandler func(c *Client, req *http.HttpRequest, resp *http.HttpResponse, err error) (*http.HttpResponse, error) + +var defaultResponseHandlers = []ReponseHandler{errorHandler, logHandler, retryHandler} +var defaultHttpResponseHandlers = []HttpReponseHandler{errorHTTPHandler, logDebugHTTPHandler} + +func retryHandler(c *Client, req request.Common, resp response.Common, err error) (response.Common, error) { + retryCount := req.GetRetryCount() + retryCount++ + req.SetRetryCount(retryCount) + + if !req.GetRetryable() || err == nil || !err.(uerr.Error).Retryable() { + return resp, err + } + + // if max retries number is reached, stop and raise last error + if req.GetRetryCount() > req.GetMaxretries() { + return resp, err + } + + // use exponential backoff constant as retry delay + delay := getExpBackoffDelay(retryCount) + <-time.After(delay) + + // the resp will be changed after invoke + err = c.InvokeAction(req.GetAction(), req, resp) + + return resp, err +} + +func getExpBackoffDelay(retryCount int) time.Duration { + minTime := 100 + if retryCount > 7 { + retryCount = 7 + } + + delay := (1 << (uint(retryCount) * 2)) * (rand.Intn(minTime) + minTime) + return time.Duration(delay) * time.Millisecond +} + +// errorHandler will normalize error to several specific error +func errorHandler(c *Client, req request.Common, resp response.Common, err error) (response.Common, error) { + if err != nil { + if _, ok := err.(uerr.Error); ok { + return resp, err + } + if uerr.IsNetworkError(err) { + return resp, uerr.NewClientError(uerr.ErrNetwork, err) + } + return resp, uerr.NewClientError(uerr.ErrSendRequest, err) + } + + if resp.GetRetCode() != 0 { + return resp, uerr.NewServerCodeError(resp.GetRetCode(), resp.GetMessage()) + } + + return resp, err +} + +func errorHTTPHandler(c *Client, req *http.HttpRequest, resp *http.HttpResponse, err error) (*http.HttpResponse, error) { + if statusErr, ok := err.(http.StatusError); ok { + return resp, uerr.NewServerStatusError(statusErr.StatusCode, statusErr.Message) + } + return resp, err +} + +func logHandler(c *Client, req request.Common, resp response.Common, err error) (response.Common, error) { + action := req.GetAction() + if err != nil { + log.Errorf("do %s failed, %s", action, err) + } else { + log.Infof("do %s successful!", action) + } + return resp, err +} + +func logDebugHTTPHandler(c *Client, req *http.HttpRequest, resp *http.HttpResponse, err error) (*http.HttpResponse, error) { + log.Debugf("%s", req) + + if err != nil { + log.Errorf("%s", err) + } else if resp.GetStatusCode() > 400 { + log.Warnf("%s", resp.GetStatusCode()) + } else { + log.Debugf("%s - %v", resp.GetBody(), resp.GetStatusCode()) + } + + return resp, err +} diff --git a/ucloud/log/logger.go b/ucloud/log/logger.go new file mode 100644 index 00000000..7633e203 --- /dev/null +++ b/ucloud/log/logger.go @@ -0,0 +1,54 @@ +package log + +import ( + "os" + + "github.com/Sirupsen/logrus" +) + +// Init will init with level and default output (stdout) and formatter (text without color) +func Init(level Level) { + logrus.SetLevel(logrus.Level(level)) + logrus.SetOutput(os.Stdout) + logrus.SetFormatter(&logrus.TextFormatter{ + DisableColors: false, + FullTimestamp: true, + }) +} + +type Level logrus.Level + +var ( + PanicLevel = Level(logrus.PanicLevel) + FatalLevel = Level(logrus.FatalLevel) + ErrorLevel = Level(logrus.ErrorLevel) + WarnLevel = Level(logrus.WarnLevel) + InfoLevel = Level(logrus.InfoLevel) + DebugLevel = Level(logrus.DebugLevel) + + SetLevel = func(level Level) { logrus.SetLevel(logrus.Level(level)) } + GetLevel = func() Level { return Level(logrus.GetLevel()) } + SetOutput = logrus.SetOutput + SetFormatter = logrus.SetFormatter + + WithError = logrus.WithError + WithField = logrus.WithField + + Debug = logrus.Debug + Print = logrus.Print + Info = logrus.Info + Warn = logrus.Warn + Warning = logrus.Warning + Error = logrus.Error + Panic = logrus.Panic + Fatal = logrus.Fatal + + Debugf = logrus.Debugf + Printf = logrus.Printf + Infof = logrus.Infof + Warnf = logrus.Warnf + Warningf = logrus.Warningf + Errorf = logrus.Errorf + Panicf = logrus.Panicf + Fatalf = logrus.Fatalf +) diff --git a/ucloud/marshaler.go b/ucloud/marshaler.go new file mode 100644 index 00000000..659e69c5 --- /dev/null +++ b/ucloud/marshaler.go @@ -0,0 +1,80 @@ +package ucloud + +import ( + "encoding/json" + "fmt" + "runtime" + + "github.com/pkg/errors" + + "github.com/ucloud/ucloud-sdk-go/private/protocol/http" + "github.com/ucloud/ucloud-sdk-go/ucloud/request" + "github.com/ucloud/ucloud-sdk-go/ucloud/response" + "github.com/ucloud/ucloud-sdk-go/ucloud/version" +) + +// SetupRequest will init request by client configuration +func (c *Client) SetupRequest(req request.Common) request.Common { + cfg := c.GetConfig() + + req.SetRetryable(true) + + // set optional client level variables + if len(req.GetRegion()) == 0 && len(cfg.Region) > 0 { + req.SetRegion(cfg.Region) + } + + if len(req.GetProjectId()) == 0 && len(cfg.ProjectId) > 0 { + req.SetProjectId(cfg.ProjectId) + } + + if req.GetTimeout() == 0 && cfg.Timeout != 0 { + req.WithTimeout(cfg.Timeout) + } + + if req.GetMaxretries() == 0 && cfg.MaxRetries != 0 { + req.WithRetry(cfg.MaxRetries) + } + + return req +} + +func (c *Client) buildHTTPRequest(req request.Common) (*http.HttpRequest, error) { + // convert request struct to query map + query, err := request.ToQueryMap(req) + if err != nil { + return nil, errors.Errorf("convert request to map failed, %s", err) + } + + // check credential information is avaliable + credential := c.GetCredential() + if credential == nil { + return nil, errors.Errorf("invalid credential infomation, please set it before request.") + } + + config := c.GetConfig() + httpReq := http.NewHttpRequest() + httpReq.SetURL(config.BaseUrl) + httpReq.SetMethod("GET") + + // set timeout with client configuration + httpReq.SetTimeout(config.Timeout) + + // keep query stirng is ordered and append credential signiture as the last query param + httpReq.SetQueryString(credential.BuildCredentialedQuery(query)) + + ua := fmt.Sprintf("GO/%s GO-SDK/%s %s", runtime.Version(), version.Version, config.UserAgent) + httpReq.SetHeader("User-Agent", ua) + + return &httpReq, nil +} + +// UnmarshalHTTPReponse will get body from http response and unmarshal it's data into response struct +func (c *Client) UnmarshalHTTPReponse(httpResp *http.HttpResponse, resp response.Common) error { + body := httpResp.GetBody() + if len(body) < 0 { + return nil + } + + return json.Unmarshal([]byte(body), &resp) +} diff --git a/ucloud/request/common.go b/ucloud/request/common.go new file mode 100644 index 00000000..daf8d7a2 --- /dev/null +++ b/ucloud/request/common.go @@ -0,0 +1,136 @@ +package request + +import "time" + +// Common is the common request +type Common interface { + GetAction() string + SetAction(string) error + + GetRegion() string + SetRegion(string) error + + GetProjectId() string + SetProjectId(string) error + + SetRetryCount(int) + GetRetryCount() int + + WithRetry(int) + GetMaxretries() int + + WithTimeout(time.Duration) + GetTimeout() time.Duration + + SetRequestTime(time.Time) + GetRequestTime() time.Time + + SetRetryable(retryable bool) + GetRetryable() bool +} + +// CommonBase is the base struct of common request +type CommonBase struct { + Action *string + Region *string + ProjectId *string + + maxRetries int + retryable bool + retryCount int + timeout time.Duration + requestTime time.Time +} + +// SetRetryCount will set retry count of request +func (c *CommonBase) SetRetryCount(retryCount int) { + c.retryCount = retryCount +} + +// GetRetryCount will return retry count of request +func (c *CommonBase) GetRetryCount() int { + return c.retryCount +} + +// WithRetry will set max retry count of request +func (c *CommonBase) WithRetry(maxRetries int) { + c.maxRetries = maxRetries + c.retryable = true +} + +// GetMaxretries will return max retry count of request +func (c *CommonBase) GetMaxretries() int { + return c.maxRetries +} + +// SetRetryable will set if the request is retryable +func (c *CommonBase) SetRetryable(retryable bool) { + c.retryable = retryable +} + +// GetRetryable will return if the request is retryable +func (c *CommonBase) GetRetryable() bool { + return c.retryable +} + +// WithTimeout will set timeout of request +func (c *CommonBase) WithTimeout(timeout time.Duration) { + c.timeout = timeout +} + +// GetTimeout will get timeout of request +func (c *CommonBase) GetTimeout() time.Duration { + return c.timeout +} + +// SetRequestTime will set timeout of request +func (c *CommonBase) SetRequestTime(requestTime time.Time) { + c.requestTime = requestTime +} + +// GetRequestTime will get timeout of request +func (c *CommonBase) GetRequestTime() time.Time { + return c.requestTime +} + +// GetAction will return action of request +func (c *CommonBase) GetAction() string { + if c.Action == nil { + return "" + } + return *c.Action +} + +// SetAction will set action of request +func (c *CommonBase) SetAction(val string) error { + c.Action = &val + return nil +} + +// GetRegion will return region of request +func (c *CommonBase) GetRegion() string { + if c.Region == nil { + return "" + } + return *c.Region +} + +// SetRegion will set region of request +func (c *CommonBase) SetRegion(val string) error { + c.Region = &val + return nil +} + +// GetProjectId will get project id of request +func (c *CommonBase) GetProjectId() string { + if c.ProjectId == nil { + return "" + } + return *c.ProjectId +} + +// SetProjectId will set project id of request +func (c *CommonBase) SetProjectId(val string) error { + c.ProjectId = &val + return nil +} diff --git a/ucloud/request/encoder.go b/ucloud/request/encoder.go new file mode 100644 index 00000000..bfe3a3d6 --- /dev/null +++ b/ucloud/request/encoder.go @@ -0,0 +1,119 @@ +package request + +import ( + "errors" + "fmt" + "reflect" + "strconv" +) + +// ToQueryMap will convert a request to string map +func ToQueryMap(req Common) (map[string]string, error) { + v := reflect.ValueOf(req) + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + + return encode(&v) +} + +func encodeOne(v *reflect.Value) (string, error) { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return strconv.FormatInt(v.Int(), 10), nil + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: + return strconv.FormatUint(v.Uint(), 10), nil + case reflect.Float32, reflect.Float64: + return strconv.FormatFloat(v.Float(), 'f', -1, 64), nil + case reflect.Bool: + return strconv.FormatBool(v.Bool()), nil + case reflect.String: + return v.String(), nil + case reflect.Ptr: + ptrValue := v.Elem() + return encodeOne(&ptrValue) + default: + message := fmt.Sprintf( + "Invalid variable type, type must be one of int-, uint-,"+ + " float-, bool, string and ptr, got %s", + v.Kind().String(), + ) + return "", errors.New(message) + } +} + +func encode(v *reflect.Value) (map[string]string, error) { + result := make(map[string]string) + + for i := 0; i < v.NumField(); i++ { + f := v.Field(i) + name := v.Type().Field(i).Name + + // skip unexported field + if !f.CanSet() { + continue + } + + switch f.Kind() { + case reflect.Slice, reflect.Array: + for i := 0; i < f.Len(); i++ { + item := f.Index(i) + if item.Kind() == reflect.Ptr && item.IsNil() { + continue + } + + keyPrefix := fmt.Sprintf("%s.%v", name, i) + + if item.Kind() == reflect.Struct { + kv, err := encode(&item) + if err != nil { + return result, err + } + + for k, v := range kv { + name := fmt.Sprintf("%s.%s", keyPrefix, k) + + if v != "" { + result[name] = v + } + } + } else { + s, err := encodeOne(&item) + if err != nil { + return result, err + } + + if s != "" { + result[keyPrefix] = s + } + } + } + case reflect.Struct: + m, err := encode(&f) + if err != nil { + return result, err + } + + // flatten composited struct into result map + for k, v := range m { + result[k] = v + } + default: + if f.Kind() == reflect.Ptr && f.IsNil() { + continue + } + + s, err := encodeOne(&f) + if err != nil { + return result, err + } + + // set field value into result + if s != "" { + result[name] = s + } + } + } + + return result, nil +} diff --git a/ucloud/request/request_test.go b/ucloud/request/request_test.go new file mode 100644 index 00000000..df3991de --- /dev/null +++ b/ucloud/request/request_test.go @@ -0,0 +1,121 @@ +package request + +import ( + "reflect" + "testing" +) + +func TestToQueryMap(t *testing.T) { + type Composite struct { + Region string + + unexported string + } + + type args struct { + req Common + } + + tests := []struct { + name string + args args + want map[string]string + wantErr bool + }{ + { + "Ok", + args{ + req: &struct { + CommonBase + Id int + Name string + IsValid bool + Ips []string + }{ + Id: 1, + Name: "lilei", + IsValid: true, + Ips: []string{"127.0.0.1", "192.168.1.1"}, + }, + }, + map[string]string{ + "Id": "1", + "Name": "lilei", + "IsValid": "true", + "Ips.0": "127.0.0.1", + "Ips.1": "192.168.1.1", + }, + false, + }, + { + "Partial", + args{ + req: &struct { + CommonBase + Id int + Name string + IsValid bool + Ips []string + }{ + Id: 1, + Name: "", + IsValid: true, + Ips: []string{"127.0.0.1", "192.168.1.1"}, + }, + }, + map[string]string{ + "Id": "1", + "IsValid": "true", + "Ips.0": "127.0.0.1", + "Ips.1": "192.168.1.1", + }, + false, + }, + { + "IsComposited", + args{ + req: &struct { + CommonBase + Composite + }{ + CommonBase{}, + Composite{Region: "cn-bj-2"}, + }, + }, + map[string]string{"Region": "cn-bj-2"}, + false, + }, + { + "IsCompositedByArray", + args{ + req: &struct { + CommonBase + Arr []Composite + }{ + CommonBase{}, + []Composite{ + {Region: "cn-bj2"}, + {Region: "cn-sh1"}, + }, + }, + }, + map[string]string{ + "Arr.0.Region": "cn-bj2", + "Arr.1.Region": "cn-sh1", + }, + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := ToQueryMap(tt.args.req) + if (err != nil) != tt.wantErr { + t.Errorf("requestToMap() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestToMap() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/ucloud/response/common.go b/ucloud/response/common.go new file mode 100644 index 00000000..15a85ddd --- /dev/null +++ b/ucloud/response/common.go @@ -0,0 +1,33 @@ +package response + +// Common describe a response of action, +// it is only used for ucloud open api v1 via HTTP GET and action parameters. +type Common interface { + GetRetCode() int + GetMessage() string + GetAction() string +} + +// CommonBase has common attribute and method, +// it also implement ActionResponse interface. +type CommonBase struct { + Action string + RetCode int + Message string +} + +// GetRetCode will return the error code of ucloud api +// Error is non-zero and succuess is zero +func (c *CommonBase) GetRetCode() int { + return c.RetCode +} + +// GetMessage will return the error message of ucloud api +func (c *CommonBase) GetMessage() string { + return c.Message +} + +// GetAction will return the request action of ucloud api +func (c *CommonBase) GetAction() string { + return c.Action +} diff --git a/ucloud/schema.go b/ucloud/schema.go new file mode 100644 index 00000000..26ffec2d --- /dev/null +++ b/ucloud/schema.go @@ -0,0 +1,75 @@ +package ucloud + +import ( + "time" + + "github.com/ucloud/ucloud-sdk-go/ucloud/version" +) + +// Version is the version of sdk +const Version = version.Version + +// String will return a pointer to string +func String(val string) *string { + return &val +} + +// StringValue will return a string from string pointer +func StringValue(ptr *string) string { + if ptr != nil { + return *ptr + } + return "" +} + +// Int will return a pointer to int +func Int(val int) *int { + return &val +} + +// IntValue will return a int from int pointer +func IntValue(ptr *int) int { + if ptr != nil { + return *ptr + } + return 0 +} + +// Bool will return a pointer to bool +func Bool(val bool) *bool { + return &val +} + +// BoolValue will return a bool from bool pointer +func BoolValue(ptr *bool) bool { + if ptr != nil { + return *ptr + } + return false +} + +// Float64 will return a pointer to float64 +func Float64(val float64) *float64 { + return &val +} + +// Float64Value will return a float64 from float64 pointer +func Float64Value(ptr *float64) float64 { + if ptr != nil { + return *ptr + } + return 0.0 +} + +// TimeDuration will return a pointer to time.Duration +func TimeDuration(val time.Duration) *time.Duration { + return &val +} + +// TimeDurationValue will return a time.Duration from a time.Duration pointer +func TimeDurationValue(ptr *time.Duration) time.Duration { + if ptr != nil { + return *ptr + } + return 0 +} diff --git a/ucloud/service/service.go b/ucloud/service/service.go deleted file mode 100644 index f34f9af6..00000000 --- a/ucloud/service/service.go +++ /dev/null @@ -1,110 +0,0 @@ -package service - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "reflect" - - "github.com/ucloud/ucloud-sdk-go/ucloud" - "github.com/ucloud/ucloud-sdk-go/ucloud/uclouderr" - "github.com/ucloud/ucloud-sdk-go/ucloud/utils" -) - -type Service struct { - Config *ucloud.Config - ServiceName string - APIVersion string - - BaseUrl string - HttpClient *http.Client -} - -func (s *Service) setHttpHeader(req *http.Request) { - if len(s.Config.HTTPHeader) == 0 { - return - } - - for key, value := range s.Config.HTTPHeader { - req.Header.Set(key, value) - } -} - -func (s *Service) DoRequest(action string, params interface{}, response interface{}) error { - requestURL, err := s.RequestURL(action, params) - if err != nil { - return fmt.Errorf("build request url failed, error: %s", err) - } - - httpReq, err := http.NewRequest("GET", requestURL, nil) - if err != nil { - return fmt.Errorf("new request url failed, error: %s", err) - } - s.setHttpHeader(httpReq) - httpResp, err := s.HttpClient.Do(httpReq) - if err != nil { - return fmt.Errorf("do request url failed, error: %s", err) - } - - defer httpResp.Body.Close() - body, err := ioutil.ReadAll(httpResp.Body) - - if err != nil { - return fmt.Errorf("do request url failed, error: %s", err) - } - - statusCode := httpResp.StatusCode - if statusCode >= 400 && statusCode <= 599 { - - uerr := uclouderr.UcloudError{} - err = json.Unmarshal(body, &uerr) - return &uclouderr.RequestFailed{ - UcloudError: uerr, - StatusCode: statusCode, - } - } - - if err = json.Unmarshal(body, &response); err != nil { - return fmt.Errorf("unmarshal url failed, error: %s", err) - } - - retCode := reflect.ValueOf(response).Elem().FieldByName("RetCode").Int() - if retCode != 0 { - var resp *uclouderr.UcloudError - if err = json.Unmarshal(body, &resp); err != nil { - return fmt.Errorf("unmarshal fault message failed, error:%s", err) - } - - message := reflect.ValueOf(resp).Elem().FieldByName("Message").String() - return fmt.Errorf("RetCode:%d Message:%s", retCode, message) - } - - return nil -} - -// RequestURL is fully url of api request -func (s *Service) RequestURL(action string, params interface{}) (string, error) { - if len(s.BaseUrl) == 0 { - return "", errors.New("baseUrl is not set") - } - - commonRequest := ucloud.CommonRequest{ - Action: action, - PublicKey: s.Config.Credentials.PublicKey, - ProjectId: s.Config.ProjectID, - } - - values := url.Values{} - utils.ConvertParamsToValues(commonRequest, &values) - utils.ConvertParamsToValues(params, &values) - - url, err := utils.UrlWithSignature(values, s.BaseUrl, s.Config.Credentials.PrivateKey) - if err != nil { - return "", fmt.Errorf("convert params error: %s", err) - } - - return url, nil -} diff --git a/ucloud/service/service_test.go b/ucloud/service/service_test.go deleted file mode 100644 index db5c9d94..00000000 --- a/ucloud/service/service_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package service - -import ( - "net/http" - "testing" - - "github.com/ucloud/ucloud-sdk-go/ucloud" - "github.com/ucloud/ucloud-sdk-go/ucloud/auth" -) - -type CreateUHostInstance struct { - Action string - Region string - ImageId string - CPU int - Memory int - DiskSpace int - LoginMode string - Password string - Name string - ChargeType string - Quantity int - PublicKey string -} - -var ( - config = ucloud.Config{ - Credentials: &auth.KeyPair{ - PublicKey: "ucloudsomeone@example.com1296235120854146120", - PrivateKey: "46f09bb9fab4f12dfc160dae12273d5332b5debe", - }, - } - - service = &Service{ - Config: ucloud.DefaultConfig.Merge(&config), - ServiceName: "UHost", - APIVersion: ucloud.APIVersion, - - BaseUrl: ucloud.APIBaseURL, - HttpClient: &http.Client{}, - } - - instance = CreateUHostInstance{ - Action: "CreateUHostInstance", - Region: "cn-north-01", - ImageId: "f43736e1-65a5-4bea-ad2e-8a46e18883c2", - CPU: 2, - Memory: 2048, - DiskSpace: 10, - LoginMode: "Password", - Password: "VUNsb3VkLmNu", - Name: "Host01", - ChargeType: "Month", - Quantity: 1, - PublicKey: "ucloudsomeone@example.com1296235120854146120", - } -) - -const ( - Signature = "64e0fe58642b75db052d50fd7380f79e6a0211bd" - RequestUrlWithSignature = "https://api.ucloud.cn/?Action=CreateUHostInstance&CPU=2&ChargeType=Month&DiskSpace=10&ImageId=f43736e1-65a5-4bea-ad2e-8a46e18883c2&LoginMode=Password&Memory=2048&Name=Host01&Password=VUNsb3VkLmNu&PublicKey=ucloudsomeone%40example.com1296235120854146120&Quantity=1&Region=cn-north-01&Signature=64e0fe58642b75db052d50fd7380f79e6a0211bd" - StringToBeSigned = "ActionCreateUHostInstanceCPU2ChargeTypeMonthDiskSpace10ImageIdf43736e1-65a5-4bea-ad2e-8a46e18883c2LoginModePasswordMemory2048NameHost01PasswordVUNsb3VkLmNuPublicKeyucloudsomeone@example.com1296235120854146120Quantity1Regioncn-north-0146f09bb9fab4f12dfc160dae12273d5332b5debe" -) - -func TestRequestURL(t *testing.T) { - - url, err := service.RequestURL("CreateUHostInstance", instance) - if err != nil { - t.Errorf("generate request url failed, Error:%s", err) - } - - if url != RequestUrlWithSignature { - t.Errorf("generate url failed. Expect: %s, actual: %s", RequestUrlWithSignature, url) - } -} diff --git a/ucloud/types.go b/ucloud/types.go deleted file mode 100644 index e4aa2b46..00000000 --- a/ucloud/types.go +++ /dev/null @@ -1,20 +0,0 @@ -package ucloud - -type CommonRequest struct { - Action string - PublicKey string - ProjectId string - Signature string -} - -type CommonResponse struct { - Action string - RetCode int -} - -type Resource struct { - ResourceType string - ResourceName string - ResourceId string - Zone string -} diff --git a/ucloud/uclouderr/error.go b/ucloud/uclouderr/error.go deleted file mode 100644 index 41803f49..00000000 --- a/ucloud/uclouderr/error.go +++ /dev/null @@ -1,20 +0,0 @@ -package uclouderr - -import "fmt" - -type UcloudError struct { - // Return the Code of request - RetCode int - // Returns the error details message. - Message string -} - -type RequestFailed struct { - UcloudError - StatusCode int -} - -func (r *RequestFailed) Error() string { - return fmt.Sprintf("Request Error, status code: %d, return code: %d, message: %s", - r.StatusCode, r.RetCode, r.Message) -} diff --git a/ucloud/utils/prettify.go b/ucloud/utils/prettify.go deleted file mode 100644 index 7d71852f..00000000 --- a/ucloud/utils/prettify.go +++ /dev/null @@ -1,103 +0,0 @@ -package utils - -import ( - "bytes" - "fmt" - "io" - "reflect" - "strings" -) - -// Prettify returns the string representation of a value. -func Prettify(i interface{}) string { - var buf bytes.Buffer - prettify(reflect.ValueOf(i), 0, &buf) - return buf.String() -} - -// prettify will recursively walk value v to build a textual -// representation of the value. -func prettify(v reflect.Value, indent int, buf *bytes.Buffer) { - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - strtype := v.Type().String() - if strtype == "time.Time" { - fmt.Fprintf(buf, "%s", v.Interface()) - break - } else if strings.HasPrefix(strtype, "io.") { - buf.WriteString("") - break - } - - buf.WriteString("{\n") - - names := []string{} - for i := 0; i < v.Type().NumField(); i++ { - name := v.Type().Field(i).Name - f := v.Field(i) - if name[0:1] == strings.ToLower(name[0:1]) { - continue // ignore unexported fields - } - if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice || f.Kind() == reflect.Map) && f.IsNil() { - continue // ignore unset fields - } - names = append(names, name) - } - - for i, n := range names { - val := v.FieldByName(n) - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(n + ": ") - prettify(val, indent+2, buf) - - if i < len(names)-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - case reflect.Slice: - nl, id, id2 := "", "", "" - if v.Len() > 3 { - nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) - } - buf.WriteString("[" + nl) - for i := 0; i < v.Len(); i++ { - buf.WriteString(id2) - prettify(v.Index(i), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString("," + nl) - } - } - - buf.WriteString(nl + id + "]") - case reflect.Map: - buf.WriteString("{\n") - - for i, k := range v.MapKeys() { - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(k.String() + ": ") - prettify(v.MapIndex(k), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - default: - format := "%v" - switch v.Interface().(type) { - case string: - format = "%q" - case io.ReadSeeker, io.Reader: - format = "buffer(%p)" - } - fmt.Fprintf(buf, format, v.Interface()) - } -} diff --git a/ucloud/utils/prettify_test.go b/ucloud/utils/prettify_test.go deleted file mode 100644 index dc11a49a..00000000 --- a/ucloud/utils/prettify_test.go +++ /dev/null @@ -1,11 +0,0 @@ -package utils - -import ( - "fmt" - "testing" -) - -func TestPrettify(t *testing.T) { - fmt.Println(Prettify("hello, world")) - -} diff --git a/ucloud/utils/utils.go b/ucloud/utils/utils.go deleted file mode 100644 index 87dbdd92..00000000 --- a/ucloud/utils/utils.go +++ /dev/null @@ -1,136 +0,0 @@ -package utils - -import ( - "bytes" - "encoding/json" - "fmt" - "log" - "net/url" - "reflect" - "sort" - "strconv" - - "github.com/ucloud/ucloud-sdk-go/ucloud/auth" -) - -func ConvertParamsToValues(params interface{}, values *url.Values) { - - elem := reflect.ValueOf(params) - if elem.Kind() == reflect.Ptr { - elem = elem.Elem() - } - - elemType := elem.Type() - for i := 0; i < elem.NumField(); i++ { - fieldName := elemType.Field(i).Name - - field := elem.Field(i) - kind := field.Kind() - if (kind == reflect.Ptr || - kind == reflect.Array || - kind == reflect.Slice || - kind == reflect.Map || - kind == reflect.Chan) && field.IsNil() { - continue - - } - - if kind == reflect.Ptr { - field = field.Elem() - kind = field.Kind() - } - - var v string - switch kind { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if field.Int() != 0 { - v = strconv.FormatInt(field.Int(), 10) - } - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - if field.Uint() != 0 { - v = strconv.FormatUint(field.Uint(), 10) - } - - case reflect.Float32: - v = strconv.FormatFloat(field.Float(), 'f', 4, 32) - - case reflect.Float64: - v = strconv.FormatFloat(field.Float(), 'f', 4, 64) - - case reflect.Bool: - v = strconv.FormatBool(field.Bool()) - - case reflect.String: - v = field.String() - case reflect.Slice: - switch field.Type().Elem().Kind() { - case reflect.String: - l := field.Len() - if l > 0 { - for i := 0; i < l; i++ { - v = field.Index(i).String() - if v != "" { - name := elemType.Field(i).Tag.Get("ArgName") - if name == "" { - name = fieldName - } - name = fmt.Sprintf("%s.%d", name, i) - values.Set(name, v) - } - } - continue - } - default: - - } - } - - if v != "" { - name := elemType.Field(i).Tag.Get("ArgName") - if name == "" { - name = fieldName - } - - values.Set(name, v) - } - } -} - -func UrlWithSignature(values url.Values, baseUrl, privateKey string) (string, error) { - - if values == nil { - return "", fmt.Errorf("values is empty") - } - - var buf bytes.Buffer - keys := make([]string, 0, len(values)) - for k := range values { - keys = append(keys, k) - } - sort.Strings(keys) - for _, k := range keys { - vs := values[k] - for _, v := range vs { - buf.WriteString(k) - buf.WriteString(v) - } - } - - signature, err := auth.GenerateSignature(buf.String(), privateKey) - if err != nil { - return "", fmt.Errorf("generate signature error:%s", err) - } - - return baseUrl + "?" + values.Encode() + "&Signature=" + url.QueryEscape(signature), nil -} - -func DumpVal(vals ...interface{}) { - for _, val := range vals { - prettyJSON, err := json.MarshalIndent(val, "", " ") - if err != nil { - log.Fatal(err) - } - log.Print(string(prettyJSON)) - } -} diff --git a/ucloud/utils/utils_test.go b/ucloud/utils/utils_test.go deleted file mode 100644 index d4b585bf..00000000 --- a/ucloud/utils/utils_test.go +++ /dev/null @@ -1 +0,0 @@ -package utils diff --git a/ucloud/version/version.go b/ucloud/version/version.go new file mode 100644 index 00000000..bb01e792 --- /dev/null +++ b/ucloud/version/version.go @@ -0,0 +1,5 @@ +package version + +// Version is the version of sdk +// See also semantic version: https://semver.org/ +const Version = "0.5.0" diff --git a/vendor/github.com/Sirupsen/logrus/.gitignore b/vendor/github.com/Sirupsen/logrus/.gitignore new file mode 100644 index 00000000..66be63a0 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/.gitignore @@ -0,0 +1 @@ +logrus diff --git a/vendor/github.com/Sirupsen/logrus/.travis.yml b/vendor/github.com/Sirupsen/logrus/.travis.yml new file mode 100644 index 00000000..2d8c0866 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/.travis.yml @@ -0,0 +1,8 @@ +language: go +go: + - 1.2 + - 1.3 + - 1.4 + - tip +install: + - go get -t ./... diff --git a/vendor/github.com/Sirupsen/logrus/CHANGELOG.md b/vendor/github.com/Sirupsen/logrus/CHANGELOG.md new file mode 100644 index 00000000..78f98959 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/CHANGELOG.md @@ -0,0 +1,47 @@ +# 0.8.7 + +* logrus/core: fix possible race (#216) +* logrus/doc: small typo fixes and doc improvements + + +# 0.8.6 + +* hooks/raven: allow passing an initialized client + +# 0.8.5 + +* logrus/core: revert #208 + +# 0.8.4 + +* formatter/text: fix data race (#218) + +# 0.8.3 + +* logrus/core: fix entry log level (#208) +* logrus/core: improve performance of text formatter by 40% +* logrus/core: expose `LevelHooks` type +* logrus/core: add support for DragonflyBSD and NetBSD +* formatter/text: print structs more verbosely + +# 0.8.2 + +* logrus: fix more Fatal family functions + +# 0.8.1 + +* logrus: fix not exiting on `Fatalf` and `Fatalln` + +# 0.8.0 + +* logrus: defaults to stderr instead of stdout +* hooks/sentry: add special field for `*http.Request` +* formatter/text: ignore Windows for colors + +# 0.7.3 + +* formatter/\*: allow configuration of timestamp layout + +# 0.7.2 + +* formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/Sirupsen/logrus/LICENSE b/vendor/github.com/Sirupsen/logrus/LICENSE new file mode 100644 index 00000000..f090cb42 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Simon Eskildsen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/Sirupsen/logrus/README.md b/vendor/github.com/Sirupsen/logrus/README.md new file mode 100644 index 00000000..6fa6e206 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/README.md @@ -0,0 +1,357 @@ +# Logrus :walrus: [![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus) [![godoc reference](https://godoc.org/github.com/Sirupsen/logrus?status.png)][godoc] + +Logrus is a structured logger for Go (golang), completely API compatible with +the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not +yet stable (pre 1.0). Logrus itself is completely stable and has been used in +many large deployments. The core API is unlikely to change much but please +version control your Logrus to make sure you aren't fetching latest `master` on +every build.** + +Nicely color-coded in development (when a TTY is attached, otherwise just +plain text): + +![Colored](http://i.imgur.com/PY7qMwd.png) + +With `log.Formatter = new(logrus.JSONFormatter)`, for easy parsing by logstash +or Splunk: + +```json +{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the +ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} + +{"level":"warning","msg":"The group's number increased tremendously!", +"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"A giant walrus appears!", +"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", +"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} + +{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, +"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} +``` + +With the default `log.Formatter = new(&log.TextFormatter{})` when a TTY is not +attached, the output is compatible with the +[logfmt](http://godoc.org/github.com/kr/logfmt) format: + +```text +time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 +time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 +time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true +time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 +time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 +time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true +exit status 1 +``` + +#### Example + +The simplest way to use Logrus is simply the package-level exported logger: + +```go +package main + +import ( + log "github.com/Sirupsen/logrus" +) + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + }).Info("A walrus appears") +} +``` + +Note that it's completely api-compatible with the stdlib logger, so you can +replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"` +and you'll now have the flexibility of Logrus. You can customize it all you +want: + +```go +package main + +import ( + "os" + log "github.com/Sirupsen/logrus" + "github.com/Sirupsen/logrus/hooks/airbrake" +) + +func init() { + // Log as JSON instead of the default ASCII formatter. + log.SetFormatter(&log.JSONFormatter{}) + + // Use the Airbrake hook to report errors that have Error severity or above to + // an exception tracker. You can create custom hooks, see the Hooks section. + log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development")) + + // Output to stderr instead of stdout, could also be a file. + log.SetOutput(os.Stderr) + + // Only log the warning severity or above. + log.SetLevel(log.WarnLevel) +} + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") + + log.WithFields(log.Fields{ + "omg": true, + "number": 122, + }).Warn("The group's number increased tremendously!") + + log.WithFields(log.Fields{ + "omg": true, + "number": 100, + }).Fatal("The ice breaks!") + + // A common pattern is to re-use fields between logging statements by re-using + // the logrus.Entry returned from WithFields() + contextLogger := log.WithFields(log.Fields{ + "common": "this is a common field", + "other": "I also should be logged always", + }) + + contextLogger.Info("I'll be logged with common and other field") + contextLogger.Info("Me too") +} +``` + +For more advanced usage such as logging to multiple locations from the same +application, you can also create an instance of the `logrus` Logger: + +```go +package main + +import ( + "github.com/Sirupsen/logrus" +) + +// Create a new instance of the logger. You can have any number of instances. +var log = logrus.New() + +func main() { + // The API for setting attributes is a little different than the package level + // exported logger. See Godoc. + log.Out = os.Stderr + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") +} +``` + +#### Fields + +Logrus encourages careful, structured logging though logging fields instead of +long, unparseable error messages. For example, instead of: `log.Fatalf("Failed +to send event %s to topic %s with key %d")`, you should log the much more +discoverable: + +```go +log.WithFields(log.Fields{ + "event": event, + "topic": topic, + "key": key, +}).Fatal("Failed to send event") +``` + +We've found this API forces you to think about logging in a way that produces +much more useful logging messages. We've been in countless situations where just +a single added field to a log statement that was already there would've saved us +hours. The `WithFields` call is optional. + +In general, with Logrus using any of the `printf`-family functions should be +seen as a hint you should add a field, however, you can still use the +`printf`-family functions with Logrus. + +#### Hooks + +You can add hooks for logging levels. For example to send errors to an exception +tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to +multiple places simultaneously, e.g. syslog. + +Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in +`init`: + +```go +import ( + log "github.com/Sirupsen/logrus" + "github.com/Sirupsen/logrus/hooks/airbrake" + logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog" + "log/syslog" +) + +func init() { + log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development")) + + hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") + if err != nil { + log.Error("Unable to connect to local syslog daemon") + } else { + log.AddHook(hook) + } +} +``` + + +| Hook | Description | +| ----- | ----------- | +| [Airbrake](https://github.com/Sirupsen/logrus/blob/master/hooks/airbrake/airbrake.go) | Send errors to an exception tracking service compatible with the Airbrake API. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. | +| [Papertrail](https://github.com/Sirupsen/logrus/blob/master/hooks/papertrail/papertrail.go) | Send errors to the Papertrail hosted logging service via UDP. | +| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. | +| [BugSnag](https://github.com/Sirupsen/logrus/blob/master/hooks/bugsnag/bugsnag.go) | Send errors to the Bugsnag exception tracking service. | +| [Sentry](https://github.com/Sirupsen/logrus/blob/master/hooks/sentry/sentry.go) | Send errors to the Sentry error logging and aggregation service. | +| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. | +| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) | +| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. | +| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` | +| [Graylog](https://github.com/gemnasium/logrus-hooks/tree/master/graylog) | Hook for logging to [Graylog](http://graylog2.org/) | +| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) | +| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem | +| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger | +| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail | +| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar | +| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd | +| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb | + +#### Level logging + +Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. + +```go +log.Debug("Useful debugging information.") +log.Info("Something noteworthy happened!") +log.Warn("You should probably take a look at this.") +log.Error("Something failed but I'm not quitting.") +// Calls os.Exit(1) after logging +log.Fatal("Bye.") +// Calls panic() after logging +log.Panic("I'm bailing.") +``` + +You can set the logging level on a `Logger`, then it will only log entries with +that severity or anything above it: + +```go +// Will log anything that is info or above (warn, error, fatal, panic). Default. +log.SetLevel(log.InfoLevel) +``` + +It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose +environment if your application has that. + +#### Entries + +Besides the fields added with `WithField` or `WithFields` some fields are +automatically added to all logging events: + +1. `time`. The timestamp when the entry was created. +2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after + the `AddFields` call. E.g. `Failed to send event.` +3. `level`. The logging level. E.g. `info`. + +#### Environments + +Logrus has no notion of environment. + +If you wish for hooks and formatters to only be used in specific environments, +you should handle that yourself. For example, if your application has a global +variable `Environment`, which is a string representation of the environment you +could do: + +```go +import ( + log "github.com/Sirupsen/logrus" +) + +init() { + // do something here to set environment depending on an environment variable + // or command-line flag + if Environment == "production" { + log.SetFormatter(&log.JSONFormatter{}) + } else { + // The TextFormatter is default, you don't actually have to do this. + log.SetFormatter(&log.TextFormatter{}) + } +} +``` + +This configuration is how `logrus` was intended to be used, but JSON in +production is mostly only useful if you do log aggregation with tools like +Splunk or Logstash. + +#### Formatters + +The built-in logging formatters are: + +* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise + without colors. + * *Note:* to force colored output when there is no TTY, set the `ForceColors` + field to `true`. To force no colored output even if there is a TTY set the + `DisableColors` field to `true` +* `logrus.JSONFormatter`. Logs fields as JSON. +* `logrus_logstash.LogstashFormatter`. Logs fields as Logstash Events (http://logstash.net). + + ```go + logrus.SetFormatter(&logrus_logstash.LogstashFormatter{Type: “application_name"}) + ``` + +Third party logging formatters: + +* [`zalgo`](https://github.com/aybabtme/logzalgo): invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. + +You can define your formatter by implementing the `Formatter` interface, +requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a +`Fields` type (`map[string]interface{}`) with all your fields as well as the +default ones (see Entries section above): + +```go +type MyJSONFormatter struct { +} + +log.SetFormatter(new(MyJSONFormatter)) + +func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { + // Note this doesn't include Time, Level and Message which are available on + // the Entry. Consult `godoc` on information about those fields or read the + // source of the official loggers. + serialized, err := json.Marshal(entry.Data) + if err != nil { + return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) + } + return append(serialized, '\n'), nil +} +``` + +#### Logger as an `io.Writer` + +Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. + +```go +w := logger.Writer() +defer w.Close() + +srv := http.Server{ + // create a stdlib log.Logger that writes to + // logrus.Logger. + ErrorLog: log.New(w, "", 0), +} +``` + +Each line written to that writer will be printed the usual way, using formatters +and hooks. The level for those entries is `info`. + +#### Rotation + +Log rotation is not provided with Logrus. Log rotation should be done by an +external program (like `logrotate(8)`) that can compress and delete old log +entries. It should not be a feature of the application-level logger. + + +[godoc]: https://godoc.org/github.com/Sirupsen/logrus diff --git a/vendor/github.com/Sirupsen/logrus/doc.go b/vendor/github.com/Sirupsen/logrus/doc.go new file mode 100644 index 00000000..dddd5f87 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/doc.go @@ -0,0 +1,26 @@ +/* +Package logrus is a structured logger for Go, completely API compatible with the standard library logger. + + +The simplest way to use Logrus is simply the package-level exported logger: + + package main + + import ( + log "github.com/Sirupsen/logrus" + ) + + func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "number": 1, + "size": 10, + }).Info("A walrus appears") + } + +Output: + time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 + +For a full guide visit https://github.com/Sirupsen/logrus +*/ +package logrus diff --git a/vendor/github.com/Sirupsen/logrus/entry.go b/vendor/github.com/Sirupsen/logrus/entry.go new file mode 100644 index 00000000..9ae900bc --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/entry.go @@ -0,0 +1,264 @@ +package logrus + +import ( + "bytes" + "fmt" + "io" + "os" + "time" +) + +// Defines the key when adding errors using WithError. +var ErrorKey = "error" + +// An entry is the final or intermediate Logrus logging entry. It contains all +// the fields passed with WithField{,s}. It's finally logged when Debug, Info, +// Warn, Error, Fatal or Panic is called on it. These objects can be reused and +// passed around as much as you wish to avoid field duplication. +type Entry struct { + Logger *Logger + + // Contains all the fields set by the user. + Data Fields + + // Time at which the log entry was created + Time time.Time + + // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic + Level Level + + // Message passed to Debug, Info, Warn, Error, Fatal or Panic + Message string +} + +func NewEntry(logger *Logger) *Entry { + return &Entry{ + Logger: logger, + // Default is three fields, give a little extra room + Data: make(Fields, 5), + } +} + +// Returns a reader for the entry, which is a proxy to the formatter. +func (entry *Entry) Reader() (*bytes.Buffer, error) { + serialized, err := entry.Logger.Formatter.Format(entry) + return bytes.NewBuffer(serialized), err +} + +// Returns the string representation from the reader and ultimately the +// formatter. +func (entry *Entry) String() (string, error) { + reader, err := entry.Reader() + if err != nil { + return "", err + } + + return reader.String(), err +} + +// Add an error as single field (using the key defined in ErrorKey) to the Entry. +func (entry *Entry) WithError(err error) *Entry { + return entry.WithField(ErrorKey, err) +} + +// Add a single field to the Entry. +func (entry *Entry) WithField(key string, value interface{}) *Entry { + return entry.WithFields(Fields{key: value}) +} + +// Add a map of fields to the Entry. +func (entry *Entry) WithFields(fields Fields) *Entry { + data := Fields{} + for k, v := range entry.Data { + data[k] = v + } + for k, v := range fields { + data[k] = v + } + return &Entry{Logger: entry.Logger, Data: data} +} + +// This function is not declared with a pointer value because otherwise +// race conditions will occur when using multiple goroutines +func (entry Entry) log(level Level, msg string) { + entry.Time = time.Now() + entry.Level = level + entry.Message = msg + + if err := entry.Logger.Hooks.Fire(level, &entry); err != nil { + entry.Logger.mu.Lock() + fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) + entry.Logger.mu.Unlock() + } + + reader, err := entry.Reader() + if err != nil { + entry.Logger.mu.Lock() + fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) + entry.Logger.mu.Unlock() + } + + entry.Logger.mu.Lock() + defer entry.Logger.mu.Unlock() + + _, err = io.Copy(entry.Logger.Out, reader) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) + } + + // To avoid Entry#log() returning a value that only would make sense for + // panic() to use in Entry#Panic(), we avoid the allocation by checking + // directly here. + if level <= PanicLevel { + panic(&entry) + } +} + +func (entry *Entry) Debug(args ...interface{}) { + if entry.Logger.Level >= DebugLevel { + entry.log(DebugLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Print(args ...interface{}) { + entry.Info(args...) +} + +func (entry *Entry) Info(args ...interface{}) { + if entry.Logger.Level >= InfoLevel { + entry.log(InfoLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Warn(args ...interface{}) { + if entry.Logger.Level >= WarnLevel { + entry.log(WarnLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Warning(args ...interface{}) { + entry.Warn(args...) +} + +func (entry *Entry) Error(args ...interface{}) { + if entry.Logger.Level >= ErrorLevel { + entry.log(ErrorLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Fatal(args ...interface{}) { + if entry.Logger.Level >= FatalLevel { + entry.log(FatalLevel, fmt.Sprint(args...)) + } + os.Exit(1) +} + +func (entry *Entry) Panic(args ...interface{}) { + if entry.Logger.Level >= PanicLevel { + entry.log(PanicLevel, fmt.Sprint(args...)) + } + panic(fmt.Sprint(args...)) +} + +// Entry Printf family functions + +func (entry *Entry) Debugf(format string, args ...interface{}) { + if entry.Logger.Level >= DebugLevel { + entry.Debug(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Infof(format string, args ...interface{}) { + if entry.Logger.Level >= InfoLevel { + entry.Info(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Printf(format string, args ...interface{}) { + entry.Infof(format, args...) +} + +func (entry *Entry) Warnf(format string, args ...interface{}) { + if entry.Logger.Level >= WarnLevel { + entry.Warn(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Warningf(format string, args ...interface{}) { + entry.Warnf(format, args...) +} + +func (entry *Entry) Errorf(format string, args ...interface{}) { + if entry.Logger.Level >= ErrorLevel { + entry.Error(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Fatalf(format string, args ...interface{}) { + if entry.Logger.Level >= FatalLevel { + entry.Fatal(fmt.Sprintf(format, args...)) + } + os.Exit(1) +} + +func (entry *Entry) Panicf(format string, args ...interface{}) { + if entry.Logger.Level >= PanicLevel { + entry.Panic(fmt.Sprintf(format, args...)) + } +} + +// Entry Println family functions + +func (entry *Entry) Debugln(args ...interface{}) { + if entry.Logger.Level >= DebugLevel { + entry.Debug(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Infoln(args ...interface{}) { + if entry.Logger.Level >= InfoLevel { + entry.Info(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Println(args ...interface{}) { + entry.Infoln(args...) +} + +func (entry *Entry) Warnln(args ...interface{}) { + if entry.Logger.Level >= WarnLevel { + entry.Warn(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Warningln(args ...interface{}) { + entry.Warnln(args...) +} + +func (entry *Entry) Errorln(args ...interface{}) { + if entry.Logger.Level >= ErrorLevel { + entry.Error(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Fatalln(args ...interface{}) { + if entry.Logger.Level >= FatalLevel { + entry.Fatal(entry.sprintlnn(args...)) + } + os.Exit(1) +} + +func (entry *Entry) Panicln(args ...interface{}) { + if entry.Logger.Level >= PanicLevel { + entry.Panic(entry.sprintlnn(args...)) + } +} + +// Sprintlnn => Sprint no newline. This is to get the behavior of how +// fmt.Sprintln where spaces are always added between operands, regardless of +// their type. Instead of vendoring the Sprintln implementation to spare a +// string allocation, we do the simplest thing. +func (entry *Entry) sprintlnn(args ...interface{}) string { + msg := fmt.Sprintln(args...) + return msg[:len(msg)-1] +} diff --git a/vendor/github.com/Sirupsen/logrus/exported.go b/vendor/github.com/Sirupsen/logrus/exported.go new file mode 100644 index 00000000..9a0120ac --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/exported.go @@ -0,0 +1,193 @@ +package logrus + +import ( + "io" +) + +var ( + // std is the name of the standard logger in stdlib `log` + std = New() +) + +func StandardLogger() *Logger { + return std +} + +// SetOutput sets the standard logger output. +func SetOutput(out io.Writer) { + std.mu.Lock() + defer std.mu.Unlock() + std.Out = out +} + +// SetFormatter sets the standard logger formatter. +func SetFormatter(formatter Formatter) { + std.mu.Lock() + defer std.mu.Unlock() + std.Formatter = formatter +} + +// SetLevel sets the standard logger level. +func SetLevel(level Level) { + std.mu.Lock() + defer std.mu.Unlock() + std.Level = level +} + +// GetLevel returns the standard logger level. +func GetLevel() Level { + std.mu.Lock() + defer std.mu.Unlock() + return std.Level +} + +// AddHook adds a hook to the standard logger hooks. +func AddHook(hook Hook) { + std.mu.Lock() + defer std.mu.Unlock() + std.Hooks.Add(hook) +} + +// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. +func WithError(err error) *Entry { + return std.WithField(ErrorKey, err) +} + +// WithField creates an entry from the standard logger and adds a field to +// it. If you want multiple fields, use `WithFields`. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithField(key string, value interface{}) *Entry { + return std.WithField(key, value) +} + +// WithFields creates an entry from the standard logger and adds multiple +// fields to it. This is simply a helper for `WithField`, invoking it +// once for each field. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithFields(fields Fields) *Entry { + return std.WithFields(fields) +} + +// Debug logs a message at level Debug on the standard logger. +func Debug(args ...interface{}) { + std.Debug(args...) +} + +// Print logs a message at level Info on the standard logger. +func Print(args ...interface{}) { + std.Print(args...) +} + +// Info logs a message at level Info on the standard logger. +func Info(args ...interface{}) { + std.Info(args...) +} + +// Warn logs a message at level Warn on the standard logger. +func Warn(args ...interface{}) { + std.Warn(args...) +} + +// Warning logs a message at level Warn on the standard logger. +func Warning(args ...interface{}) { + std.Warning(args...) +} + +// Error logs a message at level Error on the standard logger. +func Error(args ...interface{}) { + std.Error(args...) +} + +// Panic logs a message at level Panic on the standard logger. +func Panic(args ...interface{}) { + std.Panic(args...) +} + +// Fatal logs a message at level Fatal on the standard logger. +func Fatal(args ...interface{}) { + std.Fatal(args...) +} + +// Debugf logs a message at level Debug on the standard logger. +func Debugf(format string, args ...interface{}) { + std.Debugf(format, args...) +} + +// Printf logs a message at level Info on the standard logger. +func Printf(format string, args ...interface{}) { + std.Printf(format, args...) +} + +// Infof logs a message at level Info on the standard logger. +func Infof(format string, args ...interface{}) { + std.Infof(format, args...) +} + +// Warnf logs a message at level Warn on the standard logger. +func Warnf(format string, args ...interface{}) { + std.Warnf(format, args...) +} + +// Warningf logs a message at level Warn on the standard logger. +func Warningf(format string, args ...interface{}) { + std.Warningf(format, args...) +} + +// Errorf logs a message at level Error on the standard logger. +func Errorf(format string, args ...interface{}) { + std.Errorf(format, args...) +} + +// Panicf logs a message at level Panic on the standard logger. +func Panicf(format string, args ...interface{}) { + std.Panicf(format, args...) +} + +// Fatalf logs a message at level Fatal on the standard logger. +func Fatalf(format string, args ...interface{}) { + std.Fatalf(format, args...) +} + +// Debugln logs a message at level Debug on the standard logger. +func Debugln(args ...interface{}) { + std.Debugln(args...) +} + +// Println logs a message at level Info on the standard logger. +func Println(args ...interface{}) { + std.Println(args...) +} + +// Infoln logs a message at level Info on the standard logger. +func Infoln(args ...interface{}) { + std.Infoln(args...) +} + +// Warnln logs a message at level Warn on the standard logger. +func Warnln(args ...interface{}) { + std.Warnln(args...) +} + +// Warningln logs a message at level Warn on the standard logger. +func Warningln(args ...interface{}) { + std.Warningln(args...) +} + +// Errorln logs a message at level Error on the standard logger. +func Errorln(args ...interface{}) { + std.Errorln(args...) +} + +// Panicln logs a message at level Panic on the standard logger. +func Panicln(args ...interface{}) { + std.Panicln(args...) +} + +// Fatalln logs a message at level Fatal on the standard logger. +func Fatalln(args ...interface{}) { + std.Fatalln(args...) +} diff --git a/vendor/github.com/Sirupsen/logrus/formatter.go b/vendor/github.com/Sirupsen/logrus/formatter.go new file mode 100644 index 00000000..104d689f --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/formatter.go @@ -0,0 +1,48 @@ +package logrus + +import "time" + +const DefaultTimestampFormat = time.RFC3339 + +// The Formatter interface is used to implement a custom Formatter. It takes an +// `Entry`. It exposes all the fields, including the default ones: +// +// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. +// * `entry.Data["time"]`. The timestamp. +// * `entry.Data["level"]. The level the entry was logged at. +// +// Any additional fields added with `WithField` or `WithFields` are also in +// `entry.Data`. Format is expected to return an array of bytes which are then +// logged to `logger.Out`. +type Formatter interface { + Format(*Entry) ([]byte, error) +} + +// This is to not silently overwrite `time`, `msg` and `level` fields when +// dumping it. If this code wasn't there doing: +// +// logrus.WithField("level", 1).Info("hello") +// +// Would just silently drop the user provided level. Instead with this code +// it'll logged as: +// +// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} +// +// It's not exported because it's still using Data in an opinionated way. It's to +// avoid code duplication between the two default formatters. +func prefixFieldClashes(data Fields) { + _, ok := data["time"] + if ok { + data["fields.time"] = data["time"] + } + + _, ok = data["msg"] + if ok { + data["fields.msg"] = data["msg"] + } + + _, ok = data["level"] + if ok { + data["fields.level"] = data["level"] + } +} diff --git a/vendor/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/Sirupsen/logrus/hooks.go new file mode 100644 index 00000000..3f151cdc --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/hooks.go @@ -0,0 +1,34 @@ +package logrus + +// A hook to be fired when logging on the logging levels returned from +// `Levels()` on your implementation of the interface. Note that this is not +// fired in a goroutine or a channel with workers, you should handle such +// functionality yourself if your call is non-blocking and you don't wish for +// the logging calls for levels returned from `Levels()` to block. +type Hook interface { + Levels() []Level + Fire(*Entry) error +} + +// Internal type for storing the hooks on a logger instance. +type LevelHooks map[Level][]Hook + +// Add a hook to an instance of logger. This is called with +// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. +func (hooks LevelHooks) Add(hook Hook) { + for _, level := range hook.Levels() { + hooks[level] = append(hooks[level], hook) + } +} + +// Fire all the hooks for the passed level. Used by `entry.log` to fire +// appropriate hooks for a log entry. +func (hooks LevelHooks) Fire(level Level, entry *Entry) error { + for _, hook := range hooks[level] { + if err := hook.Fire(entry); err != nil { + return err + } + } + + return nil +} diff --git a/vendor/github.com/Sirupsen/logrus/json_formatter.go b/vendor/github.com/Sirupsen/logrus/json_formatter.go new file mode 100644 index 00000000..2ad6dc5c --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/json_formatter.go @@ -0,0 +1,41 @@ +package logrus + +import ( + "encoding/json" + "fmt" +) + +type JSONFormatter struct { + // TimestampFormat sets the format used for marshaling timestamps. + TimestampFormat string +} + +func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { + data := make(Fields, len(entry.Data)+3) + for k, v := range entry.Data { + switch v := v.(type) { + case error: + // Otherwise errors are ignored by `encoding/json` + // https://github.com/Sirupsen/logrus/issues/137 + data[k] = v.Error() + default: + data[k] = v + } + } + prefixFieldClashes(data) + + timestampFormat := f.TimestampFormat + if timestampFormat == "" { + timestampFormat = DefaultTimestampFormat + } + + data["time"] = entry.Time.Format(timestampFormat) + data["msg"] = entry.Message + data["level"] = entry.Level.String() + + serialized, err := json.Marshal(data) + if err != nil { + return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) + } + return append(serialized, '\n'), nil +} diff --git a/vendor/github.com/Sirupsen/logrus/logger.go b/vendor/github.com/Sirupsen/logrus/logger.go new file mode 100644 index 00000000..fd9804c6 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/logger.go @@ -0,0 +1,206 @@ +package logrus + +import ( + "io" + "os" + "sync" +) + +type Logger struct { + // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a + // file, or leave it default which is `os.Stderr`. You can also set this to + // something more adventorous, such as logging to Kafka. + Out io.Writer + // Hooks for the logger instance. These allow firing events based on logging + // levels and log entries. For example, to send errors to an error tracking + // service, log to StatsD or dump the core on fatal errors. + Hooks LevelHooks + // All log entries pass through the formatter before logged to Out. The + // included formatters are `TextFormatter` and `JSONFormatter` for which + // TextFormatter is the default. In development (when a TTY is attached) it + // logs with colors, but to a file it wouldn't. You can easily implement your + // own that implements the `Formatter` interface, see the `README` or included + // formatters for examples. + Formatter Formatter + // The logging level the logger should log at. This is typically (and defaults + // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be + // logged. `logrus.Debug` is useful in + Level Level + // Used to sync writing to the log. + mu sync.Mutex +} + +// Creates a new logger. Configuration should be set by changing `Formatter`, +// `Out` and `Hooks` directly on the default logger instance. You can also just +// instantiate your own: +// +// var log = &Logger{ +// Out: os.Stderr, +// Formatter: new(JSONFormatter), +// Hooks: make(LevelHooks), +// Level: logrus.DebugLevel, +// } +// +// It's recommended to make this a global instance called `log`. +func New() *Logger { + return &Logger{ + Out: os.Stderr, + Formatter: new(TextFormatter), + Hooks: make(LevelHooks), + Level: InfoLevel, + } +} + +// Adds a field to the log entry, note that you it doesn't log until you call +// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry. +// If you want multiple fields, use `WithFields`. +func (logger *Logger) WithField(key string, value interface{}) *Entry { + return NewEntry(logger).WithField(key, value) +} + +// Adds a struct of fields to the log entry. All it does is call `WithField` for +// each `Field`. +func (logger *Logger) WithFields(fields Fields) *Entry { + return NewEntry(logger).WithFields(fields) +} + +func (logger *Logger) Debugf(format string, args ...interface{}) { + if logger.Level >= DebugLevel { + NewEntry(logger).Debugf(format, args...) + } +} + +func (logger *Logger) Infof(format string, args ...interface{}) { + if logger.Level >= InfoLevel { + NewEntry(logger).Infof(format, args...) + } +} + +func (logger *Logger) Printf(format string, args ...interface{}) { + NewEntry(logger).Printf(format, args...) +} + +func (logger *Logger) Warnf(format string, args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warnf(format, args...) + } +} + +func (logger *Logger) Warningf(format string, args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warnf(format, args...) + } +} + +func (logger *Logger) Errorf(format string, args ...interface{}) { + if logger.Level >= ErrorLevel { + NewEntry(logger).Errorf(format, args...) + } +} + +func (logger *Logger) Fatalf(format string, args ...interface{}) { + if logger.Level >= FatalLevel { + NewEntry(logger).Fatalf(format, args...) + } + os.Exit(1) +} + +func (logger *Logger) Panicf(format string, args ...interface{}) { + if logger.Level >= PanicLevel { + NewEntry(logger).Panicf(format, args...) + } +} + +func (logger *Logger) Debug(args ...interface{}) { + if logger.Level >= DebugLevel { + NewEntry(logger).Debug(args...) + } +} + +func (logger *Logger) Info(args ...interface{}) { + if logger.Level >= InfoLevel { + NewEntry(logger).Info(args...) + } +} + +func (logger *Logger) Print(args ...interface{}) { + NewEntry(logger).Info(args...) +} + +func (logger *Logger) Warn(args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warn(args...) + } +} + +func (logger *Logger) Warning(args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warn(args...) + } +} + +func (logger *Logger) Error(args ...interface{}) { + if logger.Level >= ErrorLevel { + NewEntry(logger).Error(args...) + } +} + +func (logger *Logger) Fatal(args ...interface{}) { + if logger.Level >= FatalLevel { + NewEntry(logger).Fatal(args...) + } + os.Exit(1) +} + +func (logger *Logger) Panic(args ...interface{}) { + if logger.Level >= PanicLevel { + NewEntry(logger).Panic(args...) + } +} + +func (logger *Logger) Debugln(args ...interface{}) { + if logger.Level >= DebugLevel { + NewEntry(logger).Debugln(args...) + } +} + +func (logger *Logger) Infoln(args ...interface{}) { + if logger.Level >= InfoLevel { + NewEntry(logger).Infoln(args...) + } +} + +func (logger *Logger) Println(args ...interface{}) { + NewEntry(logger).Println(args...) +} + +func (logger *Logger) Warnln(args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warnln(args...) + } +} + +func (logger *Logger) Warningln(args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warnln(args...) + } +} + +func (logger *Logger) Errorln(args ...interface{}) { + if logger.Level >= ErrorLevel { + NewEntry(logger).Errorln(args...) + } +} + +func (logger *Logger) Fatalln(args ...interface{}) { + if logger.Level >= FatalLevel { + NewEntry(logger).Fatalln(args...) + } + os.Exit(1) +} + +func (logger *Logger) Panicln(args ...interface{}) { + if logger.Level >= PanicLevel { + NewEntry(logger).Panicln(args...) + } +} diff --git a/vendor/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/Sirupsen/logrus/logrus.go new file mode 100644 index 00000000..0c09fbc2 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/logrus.go @@ -0,0 +1,98 @@ +package logrus + +import ( + "fmt" + "log" +) + +// Fields type, used to pass to `WithFields`. +type Fields map[string]interface{} + +// Level type +type Level uint8 + +// Convert the Level to a string. E.g. PanicLevel becomes "panic". +func (level Level) String() string { + switch level { + case DebugLevel: + return "debug" + case InfoLevel: + return "info" + case WarnLevel: + return "warning" + case ErrorLevel: + return "error" + case FatalLevel: + return "fatal" + case PanicLevel: + return "panic" + } + + return "unknown" +} + +// ParseLevel takes a string level and returns the Logrus log level constant. +func ParseLevel(lvl string) (Level, error) { + switch lvl { + case "panic": + return PanicLevel, nil + case "fatal": + return FatalLevel, nil + case "error": + return ErrorLevel, nil + case "warn", "warning": + return WarnLevel, nil + case "info": + return InfoLevel, nil + case "debug": + return DebugLevel, nil + } + + var l Level + return l, fmt.Errorf("not a valid logrus Level: %q", lvl) +} + +// These are the different logging levels. You can set the logging level to log +// on your instance of logger, obtained with `logrus.New()`. +const ( + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel Level = iota + // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel +) + +// Won't compile if StdLogger can't be realized by a log.Logger +var ( + _ StdLogger = &log.Logger{} + _ StdLogger = &Entry{} + _ StdLogger = &Logger{} +) + +// StdLogger is what your logrus-enabled library should take, that way +// it'll accept a stdlib logger and a logrus logger. There's no standard +// interface, this is the closest we get, unfortunately. +type StdLogger interface { + Print(...interface{}) + Printf(string, ...interface{}) + Println(...interface{}) + + Fatal(...interface{}) + Fatalf(string, ...interface{}) + Fatalln(...interface{}) + + Panic(...interface{}) + Panicf(string, ...interface{}) + Panicln(...interface{}) +} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go b/vendor/github.com/Sirupsen/logrus/terminal_bsd.go new file mode 100644 index 00000000..71f8d67a --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/terminal_bsd.go @@ -0,0 +1,9 @@ +// +build darwin freebsd openbsd netbsd dragonfly + +package logrus + +import "syscall" + +const ioctlReadTermios = syscall.TIOCGETA + +type Termios syscall.Termios diff --git a/vendor/github.com/Sirupsen/logrus/terminal_linux.go b/vendor/github.com/Sirupsen/logrus/terminal_linux.go new file mode 100644 index 00000000..a2c0b40d --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/terminal_linux.go @@ -0,0 +1,12 @@ +// Based on ssh/terminal: +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package logrus + +import "syscall" + +const ioctlReadTermios = syscall.TCGETS + +type Termios syscall.Termios diff --git a/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go b/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go new file mode 100644 index 00000000..4bb53760 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go @@ -0,0 +1,21 @@ +// Based on ssh/terminal: +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build linux darwin freebsd openbsd netbsd dragonfly + +package logrus + +import ( + "syscall" + "unsafe" +) + +// IsTerminal returns true if the given file descriptor is a terminal. +func IsTerminal() bool { + fd := syscall.Stdout + var termios Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 +} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_windows.go b/vendor/github.com/Sirupsen/logrus/terminal_windows.go new file mode 100644 index 00000000..2e09f6f7 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/terminal_windows.go @@ -0,0 +1,27 @@ +// Based on ssh/terminal: +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build windows + +package logrus + +import ( + "syscall" + "unsafe" +) + +var kernel32 = syscall.NewLazyDLL("kernel32.dll") + +var ( + procGetConsoleMode = kernel32.NewProc("GetConsoleMode") +) + +// IsTerminal returns true if the given file descriptor is a terminal. +func IsTerminal() bool { + fd := syscall.Stdout + var st uint32 + r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0) + return r != 0 && e == 0 +} diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/Sirupsen/logrus/text_formatter.go new file mode 100644 index 00000000..17cc2984 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/text_formatter.go @@ -0,0 +1,159 @@ +package logrus + +import ( + "bytes" + "fmt" + "runtime" + "sort" + "strings" + "time" +) + +const ( + nocolor = 0 + red = 31 + green = 32 + yellow = 33 + blue = 34 + gray = 37 +) + +var ( + baseTimestamp time.Time + isTerminal bool +) + +func init() { + baseTimestamp = time.Now() + isTerminal = IsTerminal() +} + +func miniTS() int { + return int(time.Since(baseTimestamp) / time.Second) +} + +type TextFormatter struct { + // Set to true to bypass checking for a TTY before outputting colors. + ForceColors bool + + // Force disabling colors. + DisableColors bool + + // Disable timestamp logging. useful when output is redirected to logging + // system that already adds timestamps. + DisableTimestamp bool + + // Enable logging the full timestamp when a TTY is attached instead of just + // the time passed since beginning of execution. + FullTimestamp bool + + // TimestampFormat to use for display when a full timestamp is printed + TimestampFormat string + + // The fields are sorted by default for a consistent output. For applications + // that log extremely frequently and don't use the JSON formatter this may not + // be desired. + DisableSorting bool +} + +func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { + var keys []string = make([]string, 0, len(entry.Data)) + for k := range entry.Data { + keys = append(keys, k) + } + + if !f.DisableSorting { + sort.Strings(keys) + } + + b := &bytes.Buffer{} + + prefixFieldClashes(entry.Data) + + isColorTerminal := isTerminal && (runtime.GOOS != "windows") + isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors + + timestampFormat := f.TimestampFormat + if timestampFormat == "" { + timestampFormat = DefaultTimestampFormat + } + if isColored { + f.printColored(b, entry, keys, timestampFormat) + } else { + if !f.DisableTimestamp { + f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat)) + } + f.appendKeyValue(b, "level", entry.Level.String()) + f.appendKeyValue(b, "msg", entry.Message) + for _, key := range keys { + f.appendKeyValue(b, key, entry.Data[key]) + } + } + + b.WriteByte('\n') + return b.Bytes(), nil +} + +func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) { + var levelColor int + switch entry.Level { + case DebugLevel: + levelColor = gray + case WarnLevel: + levelColor = yellow + case ErrorLevel, FatalLevel, PanicLevel: + levelColor = red + default: + levelColor = blue + } + + levelText := strings.ToUpper(entry.Level.String())[0:4] + + if !f.FullTimestamp { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message) + } else { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message) + } + for _, k := range keys { + v := entry.Data[k] + fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v) + } +} + +func needsQuoting(text string) bool { + for _, ch := range text { + if !((ch >= 'a' && ch <= 'z') || + (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || + ch == '-' || ch == '.') { + return false + } + } + return true +} + +func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { + + b.WriteString(key) + b.WriteByte('=') + + switch value := value.(type) { + case string: + if needsQuoting(value) { + b.WriteString(value) + } else { + fmt.Fprintf(b, "%q", value) + } + case error: + errmsg := value.Error() + if needsQuoting(errmsg) { + b.WriteString(errmsg) + } else { + fmt.Fprintf(b, "%q", value) + } + default: + fmt.Fprint(b, value) + } + + b.WriteByte(' ') +} diff --git a/vendor/github.com/Sirupsen/logrus/writer.go b/vendor/github.com/Sirupsen/logrus/writer.go new file mode 100644 index 00000000..1e30b1c7 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/writer.go @@ -0,0 +1,31 @@ +package logrus + +import ( + "bufio" + "io" + "runtime" +) + +func (logger *Logger) Writer() *io.PipeWriter { + reader, writer := io.Pipe() + + go logger.writerScanner(reader) + runtime.SetFinalizer(writer, writerFinalizer) + + return writer +} + +func (logger *Logger) writerScanner(reader *io.PipeReader) { + scanner := bufio.NewScanner(reader) + for scanner.Scan() { + logger.Print(scanner.Text()) + } + if err := scanner.Err(); err != nil { + logger.Errorf("Error while reading from Writer: %s", err) + } + reader.Close() +} + +func writerFinalizer(writer *io.PipeWriter) { + writer.Close() +} diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE new file mode 100644 index 00000000..bc52e96f --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2012-2016 Dave Collins + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go new file mode 100644 index 00000000..79299478 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/bypass.go @@ -0,0 +1,145 @@ +// Copyright (c) 2015-2016 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when the code is not running on Google App Engine, compiled by GopherJS, and +// "-tags safe" is not added to the go build command line. The "disableunsafe" +// tag is deprecated and thus should not be used. +// Go versions prior to 1.4 are disabled because they use a different layout +// for interfaces which make the implementation of unsafeReflectValue more complex. +// +build !js,!appengine,!safe,!disableunsafe,go1.4 + +package spew + +import ( + "reflect" + "unsafe" +) + +const ( + // UnsafeDisabled is a build-time constant which specifies whether or + // not access to the unsafe package is available. + UnsafeDisabled = false + + // ptrSize is the size of a pointer on the current arch. + ptrSize = unsafe.Sizeof((*byte)(nil)) +) + +type flag uintptr + +var ( + // flagRO indicates whether the value field of a reflect.Value + // is read-only. + flagRO flag + + // flagAddr indicates whether the address of the reflect.Value's + // value may be taken. + flagAddr flag +) + +// flagKindMask holds the bits that make up the kind +// part of the flags field. In all the supported versions, +// it is in the lower 5 bits. +const flagKindMask = flag(0x1f) + +// Different versions of Go have used different +// bit layouts for the flags type. This table +// records the known combinations. +var okFlags = []struct { + ro, addr flag +}{{ + // From Go 1.4 to 1.5 + ro: 1 << 5, + addr: 1 << 7, +}, { + // Up to Go tip. + ro: 1<<5 | 1<<6, + addr: 1 << 8, +}} + +var flagValOffset = func() uintptr { + field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") + if !ok { + panic("reflect.Value has no flag field") + } + return field.Offset +}() + +// flagField returns a pointer to the flag field of a reflect.Value. +func flagField(v *reflect.Value) *flag { + return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) +} + +// unsafeReflectValue converts the passed reflect.Value into a one that bypasses +// the typical safety restrictions preventing access to unaddressable and +// unexported data. It works by digging the raw pointer to the underlying +// value out of the protected value and generating a new unprotected (unsafe) +// reflect.Value to it. +// +// This allows us to check for implementations of the Stringer and error +// interfaces to be used for pretty printing ordinarily unaddressable and +// inaccessible values such as unexported struct fields. +func unsafeReflectValue(v reflect.Value) reflect.Value { + if !v.IsValid() || (v.CanInterface() && v.CanAddr()) { + return v + } + flagFieldPtr := flagField(&v) + *flagFieldPtr &^= flagRO + *flagFieldPtr |= flagAddr + return v +} + +// Sanity checks against future reflect package changes +// to the type or semantics of the Value.flag field. +func init() { + field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") + if !ok { + panic("reflect.Value has no flag field") + } + if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { + panic("reflect.Value flag field has changed kind") + } + type t0 int + var t struct { + A t0 + // t0 will have flagEmbedRO set. + t0 + // a will have flagStickyRO set + a t0 + } + vA := reflect.ValueOf(t).FieldByName("A") + va := reflect.ValueOf(t).FieldByName("a") + vt0 := reflect.ValueOf(t).FieldByName("t0") + + // Infer flagRO from the difference between the flags + // for the (otherwise identical) fields in t. + flagPublic := *flagField(&vA) + flagWithRO := *flagField(&va) | *flagField(&vt0) + flagRO = flagPublic ^ flagWithRO + + // Infer flagAddr from the difference between a value + // taken from a pointer and not. + vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") + flagNoPtr := *flagField(&vA) + flagPtr := *flagField(&vPtrA) + flagAddr = flagNoPtr ^ flagPtr + + // Check that the inferred flags tally with one of the known versions. + for _, f := range okFlags { + if flagRO == f.ro && flagAddr == f.addr { + return + } + } + panic("reflect.Value read-only flag has changed semantics") +} diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go new file mode 100644 index 00000000..205c28d6 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go @@ -0,0 +1,38 @@ +// Copyright (c) 2015-2016 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when the code is running on Google App Engine, compiled by GopherJS, or +// "-tags safe" is added to the go build command line. The "disableunsafe" +// tag is deprecated and thus should not be used. +// +build js appengine safe disableunsafe !go1.4 + +package spew + +import "reflect" + +const ( + // UnsafeDisabled is a build-time constant which specifies whether or + // not access to the unsafe package is available. + UnsafeDisabled = true +) + +// unsafeReflectValue typically converts the passed reflect.Value into a one +// that bypasses the typical safety restrictions preventing access to +// unaddressable and unexported data. However, doing this relies on access to +// the unsafe package. This is a stub version which simply returns the passed +// reflect.Value when the unsafe package is not available. +func unsafeReflectValue(v reflect.Value) reflect.Value { + return v +} diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go new file mode 100644 index 00000000..1be8ce94 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/common.go @@ -0,0 +1,341 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "io" + "reflect" + "sort" + "strconv" +) + +// Some constants in the form of bytes to avoid string overhead. This mirrors +// the technique used in the fmt package. +var ( + panicBytes = []byte("(PANIC=") + plusBytes = []byte("+") + iBytes = []byte("i") + trueBytes = []byte("true") + falseBytes = []byte("false") + interfaceBytes = []byte("(interface {})") + commaNewlineBytes = []byte(",\n") + newlineBytes = []byte("\n") + openBraceBytes = []byte("{") + openBraceNewlineBytes = []byte("{\n") + closeBraceBytes = []byte("}") + asteriskBytes = []byte("*") + colonBytes = []byte(":") + colonSpaceBytes = []byte(": ") + openParenBytes = []byte("(") + closeParenBytes = []byte(")") + spaceBytes = []byte(" ") + pointerChainBytes = []byte("->") + nilAngleBytes = []byte("") + maxNewlineBytes = []byte("\n") + maxShortBytes = []byte("") + circularBytes = []byte("") + circularShortBytes = []byte("") + invalidAngleBytes = []byte("") + openBracketBytes = []byte("[") + closeBracketBytes = []byte("]") + percentBytes = []byte("%") + precisionBytes = []byte(".") + openAngleBytes = []byte("<") + closeAngleBytes = []byte(">") + openMapBytes = []byte("map[") + closeMapBytes = []byte("]") + lenEqualsBytes = []byte("len=") + capEqualsBytes = []byte("cap=") +) + +// hexDigits is used to map a decimal value to a hex digit. +var hexDigits = "0123456789abcdef" + +// catchPanic handles any panics that might occur during the handleMethods +// calls. +func catchPanic(w io.Writer, v reflect.Value) { + if err := recover(); err != nil { + w.Write(panicBytes) + fmt.Fprintf(w, "%v", err) + w.Write(closeParenBytes) + } +} + +// handleMethods attempts to call the Error and String methods on the underlying +// type the passed reflect.Value represents and outputes the result to Writer w. +// +// It handles panics in any called methods by catching and displaying the error +// as the formatted value. +func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { + // We need an interface to check if the type implements the error or + // Stringer interface. However, the reflect package won't give us an + // interface on certain things like unexported struct fields in order + // to enforce visibility rules. We use unsafe, when it's available, + // to bypass these restrictions since this package does not mutate the + // values. + if !v.CanInterface() { + if UnsafeDisabled { + return false + } + + v = unsafeReflectValue(v) + } + + // Choose whether or not to do error and Stringer interface lookups against + // the base type or a pointer to the base type depending on settings. + // Technically calling one of these methods with a pointer receiver can + // mutate the value, however, types which choose to satisify an error or + // Stringer interface with a pointer receiver should not be mutating their + // state inside these interface methods. + if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { + v = unsafeReflectValue(v) + } + if v.CanAddr() { + v = v.Addr() + } + + // Is it an error or Stringer? + switch iface := v.Interface().(type) { + case error: + defer catchPanic(w, v) + if cs.ContinueOnMethod { + w.Write(openParenBytes) + w.Write([]byte(iface.Error())) + w.Write(closeParenBytes) + w.Write(spaceBytes) + return false + } + + w.Write([]byte(iface.Error())) + return true + + case fmt.Stringer: + defer catchPanic(w, v) + if cs.ContinueOnMethod { + w.Write(openParenBytes) + w.Write([]byte(iface.String())) + w.Write(closeParenBytes) + w.Write(spaceBytes) + return false + } + w.Write([]byte(iface.String())) + return true + } + return false +} + +// printBool outputs a boolean value as true or false to Writer w. +func printBool(w io.Writer, val bool) { + if val { + w.Write(trueBytes) + } else { + w.Write(falseBytes) + } +} + +// printInt outputs a signed integer value to Writer w. +func printInt(w io.Writer, val int64, base int) { + w.Write([]byte(strconv.FormatInt(val, base))) +} + +// printUint outputs an unsigned integer value to Writer w. +func printUint(w io.Writer, val uint64, base int) { + w.Write([]byte(strconv.FormatUint(val, base))) +} + +// printFloat outputs a floating point value using the specified precision, +// which is expected to be 32 or 64bit, to Writer w. +func printFloat(w io.Writer, val float64, precision int) { + w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) +} + +// printComplex outputs a complex value using the specified float precision +// for the real and imaginary parts to Writer w. +func printComplex(w io.Writer, c complex128, floatPrecision int) { + r := real(c) + w.Write(openParenBytes) + w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) + i := imag(c) + if i >= 0 { + w.Write(plusBytes) + } + w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) + w.Write(iBytes) + w.Write(closeParenBytes) +} + +// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' +// prefix to Writer w. +func printHexPtr(w io.Writer, p uintptr) { + // Null pointer. + num := uint64(p) + if num == 0 { + w.Write(nilAngleBytes) + return + } + + // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix + buf := make([]byte, 18) + + // It's simpler to construct the hex string right to left. + base := uint64(16) + i := len(buf) - 1 + for num >= base { + buf[i] = hexDigits[num%base] + num /= base + i-- + } + buf[i] = hexDigits[num] + + // Add '0x' prefix. + i-- + buf[i] = 'x' + i-- + buf[i] = '0' + + // Strip unused leading bytes. + buf = buf[i:] + w.Write(buf) +} + +// valuesSorter implements sort.Interface to allow a slice of reflect.Value +// elements to be sorted. +type valuesSorter struct { + values []reflect.Value + strings []string // either nil or same len and values + cs *ConfigState +} + +// newValuesSorter initializes a valuesSorter instance, which holds a set of +// surrogate keys on which the data should be sorted. It uses flags in +// ConfigState to decide if and how to populate those surrogate keys. +func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { + vs := &valuesSorter{values: values, cs: cs} + if canSortSimply(vs.values[0].Kind()) { + return vs + } + if !cs.DisableMethods { + vs.strings = make([]string, len(values)) + for i := range vs.values { + b := bytes.Buffer{} + if !handleMethods(cs, &b, vs.values[i]) { + vs.strings = nil + break + } + vs.strings[i] = b.String() + } + } + if vs.strings == nil && cs.SpewKeys { + vs.strings = make([]string, len(values)) + for i := range vs.values { + vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) + } + } + return vs +} + +// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted +// directly, or whether it should be considered for sorting by surrogate keys +// (if the ConfigState allows it). +func canSortSimply(kind reflect.Kind) bool { + // This switch parallels valueSortLess, except for the default case. + switch kind { + case reflect.Bool: + return true + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + return true + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return true + case reflect.Float32, reflect.Float64: + return true + case reflect.String: + return true + case reflect.Uintptr: + return true + case reflect.Array: + return true + } + return false +} + +// Len returns the number of values in the slice. It is part of the +// sort.Interface implementation. +func (s *valuesSorter) Len() int { + return len(s.values) +} + +// Swap swaps the values at the passed indices. It is part of the +// sort.Interface implementation. +func (s *valuesSorter) Swap(i, j int) { + s.values[i], s.values[j] = s.values[j], s.values[i] + if s.strings != nil { + s.strings[i], s.strings[j] = s.strings[j], s.strings[i] + } +} + +// valueSortLess returns whether the first value should sort before the second +// value. It is used by valueSorter.Less as part of the sort.Interface +// implementation. +func valueSortLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Bool: + return !a.Bool() && b.Bool() + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + return a.Int() < b.Int() + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return a.Uint() < b.Uint() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.String: + return a.String() < b.String() + case reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Array: + // Compare the contents of both arrays. + l := a.Len() + for i := 0; i < l; i++ { + av := a.Index(i) + bv := b.Index(i) + if av.Interface() == bv.Interface() { + continue + } + return valueSortLess(av, bv) + } + } + return a.String() < b.String() +} + +// Less returns whether the value at index i should sort before the +// value at index j. It is part of the sort.Interface implementation. +func (s *valuesSorter) Less(i, j int) bool { + if s.strings == nil { + return valueSortLess(s.values[i], s.values[j]) + } + return s.strings[i] < s.strings[j] +} + +// sortValues is a sort function that handles both native types and any type that +// can be converted to error or Stringer. Other inputs are sorted according to +// their Value.String() value to ensure display stability. +func sortValues(values []reflect.Value, cs *ConfigState) { + if len(values) == 0 { + return + } + sort.Sort(newValuesSorter(values, cs)) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go new file mode 100644 index 00000000..2e3d22f3 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/config.go @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "io" + "os" +) + +// ConfigState houses the configuration options used by spew to format and +// display values. There is a global instance, Config, that is used to control +// all top-level Formatter and Dump functionality. Each ConfigState instance +// provides methods equivalent to the top-level functions. +// +// The zero value for ConfigState provides no indentation. You would typically +// want to set it to a space or a tab. +// +// Alternatively, you can use NewDefaultConfig to get a ConfigState instance +// with default settings. See the documentation of NewDefaultConfig for default +// values. +type ConfigState struct { + // Indent specifies the string to use for each indentation level. The + // global config instance that all top-level functions use set this to a + // single space by default. If you would like more indentation, you might + // set this to a tab with "\t" or perhaps two spaces with " ". + Indent string + + // MaxDepth controls the maximum number of levels to descend into nested + // data structures. The default, 0, means there is no limit. + // + // NOTE: Circular data structures are properly detected, so it is not + // necessary to set this value unless you specifically want to limit deeply + // nested data structures. + MaxDepth int + + // DisableMethods specifies whether or not error and Stringer interfaces are + // invoked for types that implement them. + DisableMethods bool + + // DisablePointerMethods specifies whether or not to check for and invoke + // error and Stringer interfaces on types which only accept a pointer + // receiver when the current type is not a pointer. + // + // NOTE: This might be an unsafe action since calling one of these methods + // with a pointer receiver could technically mutate the value, however, + // in practice, types which choose to satisify an error or Stringer + // interface with a pointer receiver should not be mutating their state + // inside these interface methods. As a result, this option relies on + // access to the unsafe package, so it will not have any effect when + // running in environments without access to the unsafe package such as + // Google App Engine or with the "safe" build tag specified. + DisablePointerMethods bool + + // DisablePointerAddresses specifies whether to disable the printing of + // pointer addresses. This is useful when diffing data structures in tests. + DisablePointerAddresses bool + + // DisableCapacities specifies whether to disable the printing of capacities + // for arrays, slices, maps and channels. This is useful when diffing + // data structures in tests. + DisableCapacities bool + + // ContinueOnMethod specifies whether or not recursion should continue once + // a custom error or Stringer interface is invoked. The default, false, + // means it will print the results of invoking the custom error or Stringer + // interface and return immediately instead of continuing to recurse into + // the internals of the data type. + // + // NOTE: This flag does not have any effect if method invocation is disabled + // via the DisableMethods or DisablePointerMethods options. + ContinueOnMethod bool + + // SortKeys specifies map keys should be sorted before being printed. Use + // this to have a more deterministic, diffable output. Note that only + // native types (bool, int, uint, floats, uintptr and string) and types + // that support the error or Stringer interfaces (if methods are + // enabled) are supported, with other types sorted according to the + // reflect.Value.String() output which guarantees display stability. + SortKeys bool + + // SpewKeys specifies that, as a last resort attempt, map keys should + // be spewed to strings and sorted by those strings. This is only + // considered if SortKeys is true. + SpewKeys bool +} + +// Config is the active configuration of the top-level functions. +// The configuration can be changed by modifying the contents of spew.Config. +var Config = ConfigState{Indent: " "} + +// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the formatted string as a value that satisfies error. See NewFormatter +// for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { + return fmt.Errorf(format, c.convertArgs(a)...) +} + +// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprint(w, c.convertArgs(a)...) +} + +// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + return fmt.Fprintf(w, format, c.convertArgs(a)...) +} + +// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it +// passed with a Formatter interface returned by c.NewFormatter. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, c.convertArgs(a)...) +} + +// Print is a wrapper for fmt.Print that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Print(a ...interface{}) (n int, err error) { + return fmt.Print(c.convertArgs(a)...) +} + +// Printf is a wrapper for fmt.Printf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { + return fmt.Printf(format, c.convertArgs(a)...) +} + +// Println is a wrapper for fmt.Println that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Println(a ...interface{}) (n int, err error) { + return fmt.Println(c.convertArgs(a)...) +} + +// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprint(a ...interface{}) string { + return fmt.Sprint(c.convertArgs(a)...) +} + +// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(format, c.convertArgs(a)...) +} + +// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it +// were passed with a Formatter interface returned by c.NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprintln(a ...interface{}) string { + return fmt.Sprintln(c.convertArgs(a)...) +} + +/* +NewFormatter returns a custom formatter that satisfies the fmt.Formatter +interface. As a result, it integrates cleanly with standard fmt package +printing functions. The formatter is useful for inline printing of smaller data +types similar to the standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Typically this function shouldn't be called directly. It is much easier to make +use of the custom formatter by calling one of the convenience functions such as +c.Printf, c.Println, or c.Printf. +*/ +func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { + return newFormatter(c, v) +} + +// Fdump formats and displays the passed arguments to io.Writer w. It formats +// exactly the same as Dump. +func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { + fdump(c, w, a...) +} + +/* +Dump displays the passed parameters to standard out with newlines, customizable +indentation, and additional debug information such as complete types and all +pointer addresses used to indirect to the final value. It provides the +following features over the built-in printing facilities provided by the fmt +package: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output + +The configuration options are controlled by modifying the public members +of c. See ConfigState for options documentation. + +See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to +get the formatted result as a string. +*/ +func (c *ConfigState) Dump(a ...interface{}) { + fdump(c, os.Stdout, a...) +} + +// Sdump returns a string with the passed arguments formatted exactly the same +// as Dump. +func (c *ConfigState) Sdump(a ...interface{}) string { + var buf bytes.Buffer + fdump(c, &buf, a...) + return buf.String() +} + +// convertArgs accepts a slice of arguments and returns a slice of the same +// length with each argument converted to a spew Formatter interface using +// the ConfigState associated with s. +func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { + formatters = make([]interface{}, len(args)) + for index, arg := range args { + formatters[index] = newFormatter(c, arg) + } + return formatters +} + +// NewDefaultConfig returns a ConfigState with the following default settings. +// +// Indent: " " +// MaxDepth: 0 +// DisableMethods: false +// DisablePointerMethods: false +// ContinueOnMethod: false +// SortKeys: false +func NewDefaultConfig() *ConfigState { + return &ConfigState{Indent: " "} +} diff --git a/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/davecgh/go-spew/spew/doc.go new file mode 100644 index 00000000..aacaac6f --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/doc.go @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* +Package spew implements a deep pretty printer for Go data structures to aid in +debugging. + +A quick overview of the additional features spew provides over the built-in +printing facilities for Go data types are as follows: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output (only when using + Dump style) + +There are two different approaches spew allows for dumping Go data structures: + + * Dump style which prints with newlines, customizable indentation, + and additional debug information such as types and all pointer addresses + used to indirect to the final value + * A custom Formatter interface that integrates cleanly with the standard fmt + package and replaces %v, %+v, %#v, and %#+v to provide inline printing + similar to the default %v while providing the additional functionality + outlined above and passing unsupported format verbs such as %x and %q + along to fmt + +Quick Start + +This section demonstrates how to quickly get started with spew. See the +sections below for further details on formatting and configuration options. + +To dump a variable with full newlines, indentation, type, and pointer +information use Dump, Fdump, or Sdump: + spew.Dump(myVar1, myVar2, ...) + spew.Fdump(someWriter, myVar1, myVar2, ...) + str := spew.Sdump(myVar1, myVar2, ...) + +Alternatively, if you would prefer to use format strings with a compacted inline +printing style, use the convenience wrappers Printf, Fprintf, etc with +%v (most compact), %+v (adds pointer addresses), %#v (adds types), or +%#+v (adds types and pointer addresses): + spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + +Configuration Options + +Configuration of spew is handled by fields in the ConfigState type. For +convenience, all of the top-level functions use a global state available +via the spew.Config global. + +It is also possible to create a ConfigState instance that provides methods +equivalent to the top-level functions. This allows concurrent configuration +options. See the ConfigState documentation for more details. + +The following configuration options are available: + * Indent + String to use for each indentation level for Dump functions. + It is a single space by default. A popular alternative is "\t". + + * MaxDepth + Maximum number of levels to descend into nested data structures. + There is no limit by default. + + * DisableMethods + Disables invocation of error and Stringer interface methods. + Method invocation is enabled by default. + + * DisablePointerMethods + Disables invocation of error and Stringer interface methods on types + which only accept pointer receivers from non-pointer variables. + Pointer method invocation is enabled by default. + + * DisablePointerAddresses + DisablePointerAddresses specifies whether to disable the printing of + pointer addresses. This is useful when diffing data structures in tests. + + * DisableCapacities + DisableCapacities specifies whether to disable the printing of + capacities for arrays, slices, maps and channels. This is useful when + diffing data structures in tests. + + * ContinueOnMethod + Enables recursion into types after invoking error and Stringer interface + methods. Recursion after method invocation is disabled by default. + + * SortKeys + Specifies map keys should be sorted before being printed. Use + this to have a more deterministic, diffable output. Note that + only native types (bool, int, uint, floats, uintptr and string) + and types which implement error or Stringer interfaces are + supported with other types sorted according to the + reflect.Value.String() output which guarantees display + stability. Natural map order is used by default. + + * SpewKeys + Specifies that, as a last resort attempt, map keys should be + spewed to strings and sorted by those strings. This is only + considered if SortKeys is true. + +Dump Usage + +Simply call spew.Dump with a list of variables you want to dump: + + spew.Dump(myVar1, myVar2, ...) + +You may also call spew.Fdump if you would prefer to output to an arbitrary +io.Writer. For example, to dump to standard error: + + spew.Fdump(os.Stderr, myVar1, myVar2, ...) + +A third option is to call spew.Sdump to get the formatted output as a string: + + str := spew.Sdump(myVar1, myVar2, ...) + +Sample Dump Output + +See the Dump example for details on the setup of the types and variables being +shown here. + + (main.Foo) { + unexportedField: (*main.Bar)(0xf84002e210)({ + flag: (main.Flag) flagTwo, + data: (uintptr) + }), + ExportedField: (map[interface {}]interface {}) (len=1) { + (string) (len=3) "one": (bool) true + } + } + +Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C +command as shown. + ([]uint8) (len=32 cap=32) { + 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | + 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| + 00000020 31 32 |12| + } + +Custom Formatter + +Spew provides a custom formatter that implements the fmt.Formatter interface +so that it integrates cleanly with standard fmt package printing functions. The +formatter is useful for inline printing of smaller data types similar to the +standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Custom Formatter Usage + +The simplest way to make use of the spew custom formatter is to call one of the +convenience functions such as spew.Printf, spew.Println, or spew.Printf. The +functions have syntax you are most likely already familiar with: + + spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + spew.Println(myVar, myVar2) + spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + +See the Index for the full list convenience functions. + +Sample Formatter Output + +Double pointer to a uint8: + %v: <**>5 + %+v: <**>(0xf8400420d0->0xf8400420c8)5 + %#v: (**uint8)5 + %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 + +Pointer to circular struct with a uint8 field and a pointer to itself: + %v: <*>{1 <*>} + %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} + %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} + %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} + +See the Printf example for details on the setup of variables being shown +here. + +Errors + +Since it is possible for custom Stringer/error interfaces to panic, spew +detects them and handles them internally by printing the panic information +inline with the output. Since spew is intended to provide deep pretty printing +capabilities on structures, it intentionally does not return any errors. +*/ +package spew diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go new file mode 100644 index 00000000..f78d89fc --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/dump.go @@ -0,0 +1,509 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "encoding/hex" + "fmt" + "io" + "os" + "reflect" + "regexp" + "strconv" + "strings" +) + +var ( + // uint8Type is a reflect.Type representing a uint8. It is used to + // convert cgo types to uint8 slices for hexdumping. + uint8Type = reflect.TypeOf(uint8(0)) + + // cCharRE is a regular expression that matches a cgo char. + // It is used to detect character arrays to hexdump them. + cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`) + + // cUnsignedCharRE is a regular expression that matches a cgo unsigned + // char. It is used to detect unsigned character arrays to hexdump + // them. + cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`) + + // cUint8tCharRE is a regular expression that matches a cgo uint8_t. + // It is used to detect uint8_t arrays to hexdump them. + cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`) +) + +// dumpState contains information about the state of a dump operation. +type dumpState struct { + w io.Writer + depth int + pointers map[uintptr]int + ignoreNextType bool + ignoreNextIndent bool + cs *ConfigState +} + +// indent performs indentation according to the depth level and cs.Indent +// option. +func (d *dumpState) indent() { + if d.ignoreNextIndent { + d.ignoreNextIndent = false + return + } + d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) +} + +// unpackValue returns values inside of non-nil interfaces when possible. +// This is useful for data types like structs, arrays, slices, and maps which +// can contain varying types packed inside an interface. +func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Interface && !v.IsNil() { + v = v.Elem() + } + return v +} + +// dumpPtr handles formatting of pointers by indirecting them as necessary. +func (d *dumpState) dumpPtr(v reflect.Value) { + // Remove pointers at or below the current depth from map used to detect + // circular refs. + for k, depth := range d.pointers { + if depth >= d.depth { + delete(d.pointers, k) + } + } + + // Keep list of all dereferenced pointers to show later. + pointerChain := make([]uintptr, 0) + + // Figure out how many levels of indirection there are by dereferencing + // pointers and unpacking interfaces down the chain while detecting circular + // references. + nilFound := false + cycleFound := false + indirects := 0 + ve := v + for ve.Kind() == reflect.Ptr { + if ve.IsNil() { + nilFound = true + break + } + indirects++ + addr := ve.Pointer() + pointerChain = append(pointerChain, addr) + if pd, ok := d.pointers[addr]; ok && pd < d.depth { + cycleFound = true + indirects-- + break + } + d.pointers[addr] = d.depth + + ve = ve.Elem() + if ve.Kind() == reflect.Interface { + if ve.IsNil() { + nilFound = true + break + } + ve = ve.Elem() + } + } + + // Display type information. + d.w.Write(openParenBytes) + d.w.Write(bytes.Repeat(asteriskBytes, indirects)) + d.w.Write([]byte(ve.Type().String())) + d.w.Write(closeParenBytes) + + // Display pointer information. + if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { + d.w.Write(openParenBytes) + for i, addr := range pointerChain { + if i > 0 { + d.w.Write(pointerChainBytes) + } + printHexPtr(d.w, addr) + } + d.w.Write(closeParenBytes) + } + + // Display dereferenced value. + d.w.Write(openParenBytes) + switch { + case nilFound: + d.w.Write(nilAngleBytes) + + case cycleFound: + d.w.Write(circularBytes) + + default: + d.ignoreNextType = true + d.dump(ve) + } + d.w.Write(closeParenBytes) +} + +// dumpSlice handles formatting of arrays and slices. Byte (uint8 under +// reflection) arrays and slices are dumped in hexdump -C fashion. +func (d *dumpState) dumpSlice(v reflect.Value) { + // Determine whether this type should be hex dumped or not. Also, + // for types which should be hexdumped, try to use the underlying data + // first, then fall back to trying to convert them to a uint8 slice. + var buf []uint8 + doConvert := false + doHexDump := false + numEntries := v.Len() + if numEntries > 0 { + vt := v.Index(0).Type() + vts := vt.String() + switch { + // C types that need to be converted. + case cCharRE.MatchString(vts): + fallthrough + case cUnsignedCharRE.MatchString(vts): + fallthrough + case cUint8tCharRE.MatchString(vts): + doConvert = true + + // Try to use existing uint8 slices and fall back to converting + // and copying if that fails. + case vt.Kind() == reflect.Uint8: + // We need an addressable interface to convert the type + // to a byte slice. However, the reflect package won't + // give us an interface on certain things like + // unexported struct fields in order to enforce + // visibility rules. We use unsafe, when available, to + // bypass these restrictions since this package does not + // mutate the values. + vs := v + if !vs.CanInterface() || !vs.CanAddr() { + vs = unsafeReflectValue(vs) + } + if !UnsafeDisabled { + vs = vs.Slice(0, numEntries) + + // Use the existing uint8 slice if it can be + // type asserted. + iface := vs.Interface() + if slice, ok := iface.([]uint8); ok { + buf = slice + doHexDump = true + break + } + } + + // The underlying data needs to be converted if it can't + // be type asserted to a uint8 slice. + doConvert = true + } + + // Copy and convert the underlying type if needed. + if doConvert && vt.ConvertibleTo(uint8Type) { + // Convert and copy each element into a uint8 byte + // slice. + buf = make([]uint8, numEntries) + for i := 0; i < numEntries; i++ { + vv := v.Index(i) + buf[i] = uint8(vv.Convert(uint8Type).Uint()) + } + doHexDump = true + } + } + + // Hexdump the entire slice as needed. + if doHexDump { + indent := strings.Repeat(d.cs.Indent, d.depth) + str := indent + hex.Dump(buf) + str = strings.Replace(str, "\n", "\n"+indent, -1) + str = strings.TrimRight(str, d.cs.Indent) + d.w.Write([]byte(str)) + return + } + + // Recursively call dump for each item. + for i := 0; i < numEntries; i++ { + d.dump(d.unpackValue(v.Index(i))) + if i < (numEntries - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } +} + +// dump is the main workhorse for dumping a value. It uses the passed reflect +// value to figure out what kind of object we are dealing with and formats it +// appropriately. It is a recursive function, however circular data structures +// are detected and handled properly. +func (d *dumpState) dump(v reflect.Value) { + // Handle invalid reflect values immediately. + kind := v.Kind() + if kind == reflect.Invalid { + d.w.Write(invalidAngleBytes) + return + } + + // Handle pointers specially. + if kind == reflect.Ptr { + d.indent() + d.dumpPtr(v) + return + } + + // Print type information unless already handled elsewhere. + if !d.ignoreNextType { + d.indent() + d.w.Write(openParenBytes) + d.w.Write([]byte(v.Type().String())) + d.w.Write(closeParenBytes) + d.w.Write(spaceBytes) + } + d.ignoreNextType = false + + // Display length and capacity if the built-in len and cap functions + // work with the value's kind and the len/cap itself is non-zero. + valueLen, valueCap := 0, 0 + switch v.Kind() { + case reflect.Array, reflect.Slice, reflect.Chan: + valueLen, valueCap = v.Len(), v.Cap() + case reflect.Map, reflect.String: + valueLen = v.Len() + } + if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { + d.w.Write(openParenBytes) + if valueLen != 0 { + d.w.Write(lenEqualsBytes) + printInt(d.w, int64(valueLen), 10) + } + if !d.cs.DisableCapacities && valueCap != 0 { + if valueLen != 0 { + d.w.Write(spaceBytes) + } + d.w.Write(capEqualsBytes) + printInt(d.w, int64(valueCap), 10) + } + d.w.Write(closeParenBytes) + d.w.Write(spaceBytes) + } + + // Call Stringer/error interfaces if they exist and the handle methods flag + // is enabled + if !d.cs.DisableMethods { + if (kind != reflect.Invalid) && (kind != reflect.Interface) { + if handled := handleMethods(d.cs, d.w, v); handled { + return + } + } + } + + switch kind { + case reflect.Invalid: + // Do nothing. We should never get here since invalid has already + // been handled above. + + case reflect.Bool: + printBool(d.w, v.Bool()) + + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + printInt(d.w, v.Int(), 10) + + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + printUint(d.w, v.Uint(), 10) + + case reflect.Float32: + printFloat(d.w, v.Float(), 32) + + case reflect.Float64: + printFloat(d.w, v.Float(), 64) + + case reflect.Complex64: + printComplex(d.w, v.Complex(), 32) + + case reflect.Complex128: + printComplex(d.w, v.Complex(), 64) + + case reflect.Slice: + if v.IsNil() { + d.w.Write(nilAngleBytes) + break + } + fallthrough + + case reflect.Array: + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + d.dumpSlice(v) + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.String: + d.w.Write([]byte(strconv.Quote(v.String()))) + + case reflect.Interface: + // The only time we should get here is for nil interfaces due to + // unpackValue calls. + if v.IsNil() { + d.w.Write(nilAngleBytes) + } + + case reflect.Ptr: + // Do nothing. We should never get here since pointers have already + // been handled above. + + case reflect.Map: + // nil maps should be indicated as different than empty maps + if v.IsNil() { + d.w.Write(nilAngleBytes) + break + } + + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + numEntries := v.Len() + keys := v.MapKeys() + if d.cs.SortKeys { + sortValues(keys, d.cs) + } + for i, key := range keys { + d.dump(d.unpackValue(key)) + d.w.Write(colonSpaceBytes) + d.ignoreNextIndent = true + d.dump(d.unpackValue(v.MapIndex(key))) + if i < (numEntries - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.Struct: + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + vt := v.Type() + numFields := v.NumField() + for i := 0; i < numFields; i++ { + d.indent() + vtf := vt.Field(i) + d.w.Write([]byte(vtf.Name)) + d.w.Write(colonSpaceBytes) + d.ignoreNextIndent = true + d.dump(d.unpackValue(v.Field(i))) + if i < (numFields - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.Uintptr: + printHexPtr(d.w, uintptr(v.Uint())) + + case reflect.UnsafePointer, reflect.Chan, reflect.Func: + printHexPtr(d.w, v.Pointer()) + + // There were not any other types at the time this code was written, but + // fall back to letting the default fmt package handle it in case any new + // types are added. + default: + if v.CanInterface() { + fmt.Fprintf(d.w, "%v", v.Interface()) + } else { + fmt.Fprintf(d.w, "%v", v.String()) + } + } +} + +// fdump is a helper function to consolidate the logic from the various public +// methods which take varying writers and config states. +func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { + for _, arg := range a { + if arg == nil { + w.Write(interfaceBytes) + w.Write(spaceBytes) + w.Write(nilAngleBytes) + w.Write(newlineBytes) + continue + } + + d := dumpState{w: w, cs: cs} + d.pointers = make(map[uintptr]int) + d.dump(reflect.ValueOf(arg)) + d.w.Write(newlineBytes) + } +} + +// Fdump formats and displays the passed arguments to io.Writer w. It formats +// exactly the same as Dump. +func Fdump(w io.Writer, a ...interface{}) { + fdump(&Config, w, a...) +} + +// Sdump returns a string with the passed arguments formatted exactly the same +// as Dump. +func Sdump(a ...interface{}) string { + var buf bytes.Buffer + fdump(&Config, &buf, a...) + return buf.String() +} + +/* +Dump displays the passed parameters to standard out with newlines, customizable +indentation, and additional debug information such as complete types and all +pointer addresses used to indirect to the final value. It provides the +following features over the built-in printing facilities provided by the fmt +package: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output + +The configuration options are controlled by an exported package global, +spew.Config. See ConfigState for options documentation. + +See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to +get the formatted result as a string. +*/ +func Dump(a ...interface{}) { + fdump(&Config, os.Stdout, a...) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go new file mode 100644 index 00000000..b04edb7d --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/format.go @@ -0,0 +1,419 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "reflect" + "strconv" + "strings" +) + +// supportedFlags is a list of all the character flags supported by fmt package. +const supportedFlags = "0-+# " + +// formatState implements the fmt.Formatter interface and contains information +// about the state of a formatting operation. The NewFormatter function can +// be used to get a new Formatter which can be used directly as arguments +// in standard fmt package printing calls. +type formatState struct { + value interface{} + fs fmt.State + depth int + pointers map[uintptr]int + ignoreNextType bool + cs *ConfigState +} + +// buildDefaultFormat recreates the original format string without precision +// and width information to pass in to fmt.Sprintf in the case of an +// unrecognized type. Unless new types are added to the language, this +// function won't ever be called. +func (f *formatState) buildDefaultFormat() (format string) { + buf := bytes.NewBuffer(percentBytes) + + for _, flag := range supportedFlags { + if f.fs.Flag(int(flag)) { + buf.WriteRune(flag) + } + } + + buf.WriteRune('v') + + format = buf.String() + return format +} + +// constructOrigFormat recreates the original format string including precision +// and width information to pass along to the standard fmt package. This allows +// automatic deferral of all format strings this package doesn't support. +func (f *formatState) constructOrigFormat(verb rune) (format string) { + buf := bytes.NewBuffer(percentBytes) + + for _, flag := range supportedFlags { + if f.fs.Flag(int(flag)) { + buf.WriteRune(flag) + } + } + + if width, ok := f.fs.Width(); ok { + buf.WriteString(strconv.Itoa(width)) + } + + if precision, ok := f.fs.Precision(); ok { + buf.Write(precisionBytes) + buf.WriteString(strconv.Itoa(precision)) + } + + buf.WriteRune(verb) + + format = buf.String() + return format +} + +// unpackValue returns values inside of non-nil interfaces when possible and +// ensures that types for values which have been unpacked from an interface +// are displayed when the show types flag is also set. +// This is useful for data types like structs, arrays, slices, and maps which +// can contain varying types packed inside an interface. +func (f *formatState) unpackValue(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Interface { + f.ignoreNextType = false + if !v.IsNil() { + v = v.Elem() + } + } + return v +} + +// formatPtr handles formatting of pointers by indirecting them as necessary. +func (f *formatState) formatPtr(v reflect.Value) { + // Display nil if top level pointer is nil. + showTypes := f.fs.Flag('#') + if v.IsNil() && (!showTypes || f.ignoreNextType) { + f.fs.Write(nilAngleBytes) + return + } + + // Remove pointers at or below the current depth from map used to detect + // circular refs. + for k, depth := range f.pointers { + if depth >= f.depth { + delete(f.pointers, k) + } + } + + // Keep list of all dereferenced pointers to possibly show later. + pointerChain := make([]uintptr, 0) + + // Figure out how many levels of indirection there are by derferencing + // pointers and unpacking interfaces down the chain while detecting circular + // references. + nilFound := false + cycleFound := false + indirects := 0 + ve := v + for ve.Kind() == reflect.Ptr { + if ve.IsNil() { + nilFound = true + break + } + indirects++ + addr := ve.Pointer() + pointerChain = append(pointerChain, addr) + if pd, ok := f.pointers[addr]; ok && pd < f.depth { + cycleFound = true + indirects-- + break + } + f.pointers[addr] = f.depth + + ve = ve.Elem() + if ve.Kind() == reflect.Interface { + if ve.IsNil() { + nilFound = true + break + } + ve = ve.Elem() + } + } + + // Display type or indirection level depending on flags. + if showTypes && !f.ignoreNextType { + f.fs.Write(openParenBytes) + f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) + f.fs.Write([]byte(ve.Type().String())) + f.fs.Write(closeParenBytes) + } else { + if nilFound || cycleFound { + indirects += strings.Count(ve.Type().String(), "*") + } + f.fs.Write(openAngleBytes) + f.fs.Write([]byte(strings.Repeat("*", indirects))) + f.fs.Write(closeAngleBytes) + } + + // Display pointer information depending on flags. + if f.fs.Flag('+') && (len(pointerChain) > 0) { + f.fs.Write(openParenBytes) + for i, addr := range pointerChain { + if i > 0 { + f.fs.Write(pointerChainBytes) + } + printHexPtr(f.fs, addr) + } + f.fs.Write(closeParenBytes) + } + + // Display dereferenced value. + switch { + case nilFound: + f.fs.Write(nilAngleBytes) + + case cycleFound: + f.fs.Write(circularShortBytes) + + default: + f.ignoreNextType = true + f.format(ve) + } +} + +// format is the main workhorse for providing the Formatter interface. It +// uses the passed reflect value to figure out what kind of object we are +// dealing with and formats it appropriately. It is a recursive function, +// however circular data structures are detected and handled properly. +func (f *formatState) format(v reflect.Value) { + // Handle invalid reflect values immediately. + kind := v.Kind() + if kind == reflect.Invalid { + f.fs.Write(invalidAngleBytes) + return + } + + // Handle pointers specially. + if kind == reflect.Ptr { + f.formatPtr(v) + return + } + + // Print type information unless already handled elsewhere. + if !f.ignoreNextType && f.fs.Flag('#') { + f.fs.Write(openParenBytes) + f.fs.Write([]byte(v.Type().String())) + f.fs.Write(closeParenBytes) + } + f.ignoreNextType = false + + // Call Stringer/error interfaces if they exist and the handle methods + // flag is enabled. + if !f.cs.DisableMethods { + if (kind != reflect.Invalid) && (kind != reflect.Interface) { + if handled := handleMethods(f.cs, f.fs, v); handled { + return + } + } + } + + switch kind { + case reflect.Invalid: + // Do nothing. We should never get here since invalid has already + // been handled above. + + case reflect.Bool: + printBool(f.fs, v.Bool()) + + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + printInt(f.fs, v.Int(), 10) + + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + printUint(f.fs, v.Uint(), 10) + + case reflect.Float32: + printFloat(f.fs, v.Float(), 32) + + case reflect.Float64: + printFloat(f.fs, v.Float(), 64) + + case reflect.Complex64: + printComplex(f.fs, v.Complex(), 32) + + case reflect.Complex128: + printComplex(f.fs, v.Complex(), 64) + + case reflect.Slice: + if v.IsNil() { + f.fs.Write(nilAngleBytes) + break + } + fallthrough + + case reflect.Array: + f.fs.Write(openBracketBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + numEntries := v.Len() + for i := 0; i < numEntries; i++ { + if i > 0 { + f.fs.Write(spaceBytes) + } + f.ignoreNextType = true + f.format(f.unpackValue(v.Index(i))) + } + } + f.depth-- + f.fs.Write(closeBracketBytes) + + case reflect.String: + f.fs.Write([]byte(v.String())) + + case reflect.Interface: + // The only time we should get here is for nil interfaces due to + // unpackValue calls. + if v.IsNil() { + f.fs.Write(nilAngleBytes) + } + + case reflect.Ptr: + // Do nothing. We should never get here since pointers have already + // been handled above. + + case reflect.Map: + // nil maps should be indicated as different than empty maps + if v.IsNil() { + f.fs.Write(nilAngleBytes) + break + } + + f.fs.Write(openMapBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + keys := v.MapKeys() + if f.cs.SortKeys { + sortValues(keys, f.cs) + } + for i, key := range keys { + if i > 0 { + f.fs.Write(spaceBytes) + } + f.ignoreNextType = true + f.format(f.unpackValue(key)) + f.fs.Write(colonBytes) + f.ignoreNextType = true + f.format(f.unpackValue(v.MapIndex(key))) + } + } + f.depth-- + f.fs.Write(closeMapBytes) + + case reflect.Struct: + numFields := v.NumField() + f.fs.Write(openBraceBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + vt := v.Type() + for i := 0; i < numFields; i++ { + if i > 0 { + f.fs.Write(spaceBytes) + } + vtf := vt.Field(i) + if f.fs.Flag('+') || f.fs.Flag('#') { + f.fs.Write([]byte(vtf.Name)) + f.fs.Write(colonBytes) + } + f.format(f.unpackValue(v.Field(i))) + } + } + f.depth-- + f.fs.Write(closeBraceBytes) + + case reflect.Uintptr: + printHexPtr(f.fs, uintptr(v.Uint())) + + case reflect.UnsafePointer, reflect.Chan, reflect.Func: + printHexPtr(f.fs, v.Pointer()) + + // There were not any other types at the time this code was written, but + // fall back to letting the default fmt package handle it if any get added. + default: + format := f.buildDefaultFormat() + if v.CanInterface() { + fmt.Fprintf(f.fs, format, v.Interface()) + } else { + fmt.Fprintf(f.fs, format, v.String()) + } + } +} + +// Format satisfies the fmt.Formatter interface. See NewFormatter for usage +// details. +func (f *formatState) Format(fs fmt.State, verb rune) { + f.fs = fs + + // Use standard formatting for verbs that are not v. + if verb != 'v' { + format := f.constructOrigFormat(verb) + fmt.Fprintf(fs, format, f.value) + return + } + + if f.value == nil { + if fs.Flag('#') { + fs.Write(interfaceBytes) + } + fs.Write(nilAngleBytes) + return + } + + f.format(reflect.ValueOf(f.value)) +} + +// newFormatter is a helper function to consolidate the logic from the various +// public methods which take varying config states. +func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { + fs := &formatState{value: v, cs: cs} + fs.pointers = make(map[uintptr]int) + return fs +} + +/* +NewFormatter returns a custom formatter that satisfies the fmt.Formatter +interface. As a result, it integrates cleanly with standard fmt package +printing functions. The formatter is useful for inline printing of smaller data +types similar to the standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Typically this function shouldn't be called directly. It is much easier to make +use of the custom formatter by calling one of the convenience functions such as +Printf, Println, or Fprintf. +*/ +func NewFormatter(v interface{}) fmt.Formatter { + return newFormatter(&Config, v) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/davecgh/go-spew/spew/spew.go new file mode 100644 index 00000000..32c0e338 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/spew.go @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "fmt" + "io" +) + +// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the formatted string as a value that satisfies error. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Errorf(format string, a ...interface{}) (err error) { + return fmt.Errorf(format, convertArgs(a)...) +} + +// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprint(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprint(w, convertArgs(a)...) +} + +// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + return fmt.Fprintf(w, format, convertArgs(a)...) +} + +// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it +// passed with a default Formatter interface returned by NewFormatter. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, convertArgs(a)...) +} + +// Print is a wrapper for fmt.Print that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) +func Print(a ...interface{}) (n int, err error) { + return fmt.Print(convertArgs(a)...) +} + +// Printf is a wrapper for fmt.Printf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Printf(format string, a ...interface{}) (n int, err error) { + return fmt.Printf(format, convertArgs(a)...) +} + +// Println is a wrapper for fmt.Println that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) +func Println(a ...interface{}) (n int, err error) { + return fmt.Println(convertArgs(a)...) +} + +// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprint(a ...interface{}) string { + return fmt.Sprint(convertArgs(a)...) +} + +// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(format, convertArgs(a)...) +} + +// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it +// were passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprintln(a ...interface{}) string { + return fmt.Sprintln(convertArgs(a)...) +} + +// convertArgs accepts a slice of arguments and returns a slice of the same +// length with each argument converted to a default spew Formatter interface. +func convertArgs(args []interface{}) (formatters []interface{}) { + formatters = make([]interface{}, len(args)) + for index, arg := range args { + formatters[index] = NewFormatter(arg) + } + return formatters +} diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore new file mode 100644 index 00000000..daf913b1 --- /dev/null +++ b/vendor/github.com/pkg/errors/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml new file mode 100644 index 00000000..588ceca1 --- /dev/null +++ b/vendor/github.com/pkg/errors/.travis.yml @@ -0,0 +1,11 @@ +language: go +go_import_path: github.com/pkg/errors +go: + - 1.4.3 + - 1.5.4 + - 1.6.2 + - 1.7.1 + - tip + +script: + - go test -v ./... diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE new file mode 100644 index 00000000..835ba3e7 --- /dev/null +++ b/vendor/github.com/pkg/errors/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2015, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md new file mode 100644 index 00000000..273db3c9 --- /dev/null +++ b/vendor/github.com/pkg/errors/README.md @@ -0,0 +1,52 @@ +# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) + +Package errors provides simple error handling primitives. + +`go get github.com/pkg/errors` + +The traditional error handling idiom in Go is roughly akin to +```go +if err != nil { + return err +} +``` +which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. + +## Adding context to an error + +The errors.Wrap function returns a new error that adds context to the original error. For example +```go +_, err := ioutil.ReadAll(r) +if err != nil { + return errors.Wrap(err, "read failed") +} +``` +## Retrieving the cause of an error + +Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. +```go +type causer interface { + Cause() error +} +``` +`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: +```go +switch err := errors.Cause(err).(type) { +case *MyError: + // handle specifically +default: + // unknown error +} +``` + +[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). + +## Contributing + +We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. + +Before proposing a change, please discuss your change by raising an issue. + +## Licence + +BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml new file mode 100644 index 00000000..a932eade --- /dev/null +++ b/vendor/github.com/pkg/errors/appveyor.yml @@ -0,0 +1,32 @@ +version: build-{build}.{branch} + +clone_folder: C:\gopath\src\github.com\pkg\errors +shallow_clone: true # for startup speed + +environment: + GOPATH: C:\gopath + +platform: + - x64 + +# http://www.appveyor.com/docs/installed-software +install: + # some helpful output for debugging builds + - go version + - go env + # pre-installed MinGW at C:\MinGW is 32bit only + # but MSYS2 at C:\msys64 has mingw64 + - set PATH=C:\msys64\mingw64\bin;%PATH% + - gcc --version + - g++ --version + +build_script: + - go install -v ./... + +test_script: + - set PATH=C:\gopath\bin;%PATH% + - go test -v ./... + +#artifacts: +# - path: '%GOPATH%\bin\*.exe' +deploy: off diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go new file mode 100644 index 00000000..842ee804 --- /dev/null +++ b/vendor/github.com/pkg/errors/errors.go @@ -0,0 +1,269 @@ +// Package errors provides simple error handling primitives. +// +// The traditional error handling idiom in Go is roughly akin to +// +// if err != nil { +// return err +// } +// +// which applied recursively up the call stack results in error reports +// without context or debugging information. The errors package allows +// programmers to add context to the failure path in their code in a way +// that does not destroy the original value of the error. +// +// Adding context to an error +// +// The errors.Wrap function returns a new error that adds context to the +// original error by recording a stack trace at the point Wrap is called, +// and the supplied message. For example +// +// _, err := ioutil.ReadAll(r) +// if err != nil { +// return errors.Wrap(err, "read failed") +// } +// +// If additional control is required the errors.WithStack and errors.WithMessage +// functions destructure errors.Wrap into its component operations of annotating +// an error with a stack trace and an a message, respectively. +// +// Retrieving the cause of an error +// +// Using errors.Wrap constructs a stack of errors, adding context to the +// preceding error. Depending on the nature of the error it may be necessary +// to reverse the operation of errors.Wrap to retrieve the original error +// for inspection. Any error value which implements this interface +// +// type causer interface { +// Cause() error +// } +// +// can be inspected by errors.Cause. errors.Cause will recursively retrieve +// the topmost error which does not implement causer, which is assumed to be +// the original cause. For example: +// +// switch err := errors.Cause(err).(type) { +// case *MyError: +// // handle specifically +// default: +// // unknown error +// } +// +// causer interface is not exported by this package, but is considered a part +// of stable public API. +// +// Formatted printing of errors +// +// All error values returned from this package implement fmt.Formatter and can +// be formatted by the fmt package. The following verbs are supported +// +// %s print the error. If the error has a Cause it will be +// printed recursively +// %v see %s +// %+v extended format. Each Frame of the error's StackTrace will +// be printed in detail. +// +// Retrieving the stack trace of an error or wrapper +// +// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are +// invoked. This information can be retrieved with the following interface. +// +// type stackTracer interface { +// StackTrace() errors.StackTrace +// } +// +// Where errors.StackTrace is defined as +// +// type StackTrace []Frame +// +// The Frame type represents a call site in the stack trace. Frame supports +// the fmt.Formatter interface that can be used for printing information about +// the stack trace of this error. For example: +// +// if err, ok := err.(stackTracer); ok { +// for _, f := range err.StackTrace() { +// fmt.Printf("%+s:%d", f) +// } +// } +// +// stackTracer interface is not exported by this package, but is considered a part +// of stable public API. +// +// See the documentation for Frame.Format for more details. +package errors + +import ( + "fmt" + "io" +) + +// New returns an error with the supplied message. +// New also records the stack trace at the point it was called. +func New(message string) error { + return &fundamental{ + msg: message, + stack: callers(), + } +} + +// Errorf formats according to a format specifier and returns the string +// as a value that satisfies error. +// Errorf also records the stack trace at the point it was called. +func Errorf(format string, args ...interface{}) error { + return &fundamental{ + msg: fmt.Sprintf(format, args...), + stack: callers(), + } +} + +// fundamental is an error that has a message and a stack, but no caller. +type fundamental struct { + msg string + *stack +} + +func (f *fundamental) Error() string { return f.msg } + +func (f *fundamental) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + io.WriteString(s, f.msg) + f.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, f.msg) + case 'q': + fmt.Fprintf(s, "%q", f.msg) + } +} + +// WithStack annotates err with a stack trace at the point WithStack was called. +// If err is nil, WithStack returns nil. +func WithStack(err error) error { + if err == nil { + return nil + } + return &withStack{ + err, + callers(), + } +} + +type withStack struct { + error + *stack +} + +func (w *withStack) Cause() error { return w.error } + +func (w *withStack) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v", w.Cause()) + w.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, w.Error()) + case 'q': + fmt.Fprintf(s, "%q", w.Error()) + } +} + +// Wrap returns an error annotating err with a stack trace +// at the point Wrap is called, and the supplied message. +// If err is nil, Wrap returns nil. +func Wrap(err error, message string) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: message, + } + return &withStack{ + err, + callers(), + } +} + +// Wrapf returns an error annotating err with a stack trace +// at the point Wrapf is call, and the format specifier. +// If err is nil, Wrapf returns nil. +func Wrapf(err error, format string, args ...interface{}) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: fmt.Sprintf(format, args...), + } + return &withStack{ + err, + callers(), + } +} + +// WithMessage annotates err with a new message. +// If err is nil, WithMessage returns nil. +func WithMessage(err error, message string) error { + if err == nil { + return nil + } + return &withMessage{ + cause: err, + msg: message, + } +} + +type withMessage struct { + cause error + msg string +} + +func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } +func (w *withMessage) Cause() error { return w.cause } + +func (w *withMessage) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v\n", w.Cause()) + io.WriteString(s, w.msg) + return + } + fallthrough + case 's', 'q': + io.WriteString(s, w.Error()) + } +} + +// Cause returns the underlying cause of the error, if possible. +// An error value has a cause if it implements the following +// interface: +// +// type causer interface { +// Cause() error +// } +// +// If the error does not implement Cause, the original error will +// be returned. If the error is nil, nil will be returned without further +// investigation. +func Cause(err error) error { + type causer interface { + Cause() error + } + + for err != nil { + cause, ok := err.(causer) + if !ok { + break + } + err = cause.Cause() + } + return err +} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go new file mode 100644 index 00000000..6b1f2891 --- /dev/null +++ b/vendor/github.com/pkg/errors/stack.go @@ -0,0 +1,178 @@ +package errors + +import ( + "fmt" + "io" + "path" + "runtime" + "strings" +) + +// Frame represents a program counter inside a stack frame. +type Frame uintptr + +// pc returns the program counter for this frame; +// multiple frames may have the same PC value. +func (f Frame) pc() uintptr { return uintptr(f) - 1 } + +// file returns the full path to the file that contains the +// function for this Frame's pc. +func (f Frame) file() string { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return "unknown" + } + file, _ := fn.FileLine(f.pc()) + return file +} + +// line returns the line number of source code of the +// function for this Frame's pc. +func (f Frame) line() int { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return 0 + } + _, line := fn.FileLine(f.pc()) + return line +} + +// Format formats the frame according to the fmt.Formatter interface. +// +// %s source file +// %d source line +// %n function name +// %v equivalent to %s:%d +// +// Format accepts flags that alter the printing of some verbs, as follows: +// +// %+s path of source file relative to the compile time GOPATH +// %+v equivalent to %+s:%d +func (f Frame) Format(s fmt.State, verb rune) { + switch verb { + case 's': + switch { + case s.Flag('+'): + pc := f.pc() + fn := runtime.FuncForPC(pc) + if fn == nil { + io.WriteString(s, "unknown") + } else { + file, _ := fn.FileLine(pc) + fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) + } + default: + io.WriteString(s, path.Base(f.file())) + } + case 'd': + fmt.Fprintf(s, "%d", f.line()) + case 'n': + name := runtime.FuncForPC(f.pc()).Name() + io.WriteString(s, funcname(name)) + case 'v': + f.Format(s, 's') + io.WriteString(s, ":") + f.Format(s, 'd') + } +} + +// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). +type StackTrace []Frame + +func (st StackTrace) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case s.Flag('+'): + for _, f := range st { + fmt.Fprintf(s, "\n%+v", f) + } + case s.Flag('#'): + fmt.Fprintf(s, "%#v", []Frame(st)) + default: + fmt.Fprintf(s, "%v", []Frame(st)) + } + case 's': + fmt.Fprintf(s, "%s", []Frame(st)) + } +} + +// stack represents a stack of program counters. +type stack []uintptr + +func (s *stack) Format(st fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case st.Flag('+'): + for _, pc := range *s { + f := Frame(pc) + fmt.Fprintf(st, "\n%+v", f) + } + } + } +} + +func (s *stack) StackTrace() StackTrace { + f := make([]Frame, len(*s)) + for i := 0; i < len(f); i++ { + f[i] = Frame((*s)[i]) + } + return f +} + +func callers() *stack { + const depth = 32 + var pcs [depth]uintptr + n := runtime.Callers(3, pcs[:]) + var st stack = pcs[0:n] + return &st +} + +// funcname removes the path prefix component of a function's name reported by func.Name(). +func funcname(name string) string { + i := strings.LastIndex(name, "/") + name = name[i+1:] + i = strings.Index(name, ".") + return name[i+1:] +} + +func trimGOPATH(name, file string) string { + // Here we want to get the source file path relative to the compile time + // GOPATH. As of Go 1.6.x there is no direct way to know the compiled + // GOPATH at runtime, but we can infer the number of path segments in the + // GOPATH. We note that fn.Name() returns the function name qualified by + // the import path, which does not include the GOPATH. Thus we can trim + // segments from the beginning of the file path until the number of path + // separators remaining is one more than the number of path separators in + // the function name. For example, given: + // + // GOPATH /home/user + // file /home/user/src/pkg/sub/file.go + // fn.Name() pkg/sub.Type.Method + // + // We want to produce: + // + // pkg/sub/file.go + // + // From this we can easily see that fn.Name() has one less path separator + // than our desired output. We count separators from the end of the file + // path until it finds two more than in the function name and then move + // one character forward to preserve the initial path segment without a + // leading separator. + const sep = "/" + goal := strings.Count(name, sep) + 2 + i := len(file) + for n := 0; n < goal; n++ { + i = strings.LastIndex(file[:i], sep) + if i == -1 { + // not enough separators found, set i so that the slice expression + // below leaves file unmodified + i = -len(sep) + break + } + } + // get back to 0 or trim the leading separator + file = file[i+len(sep):] + return file +} diff --git a/vendor/github.com/pmezard/go-difflib/LICENSE b/vendor/github.com/pmezard/go-difflib/LICENSE new file mode 100644 index 00000000..c67dad61 --- /dev/null +++ b/vendor/github.com/pmezard/go-difflib/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2013, Patrick Mezard +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + The names of its contributors may not be used to endorse or promote +products derived from this software without specific prior written +permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go new file mode 100644 index 00000000..003e99fa --- /dev/null +++ b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go @@ -0,0 +1,772 @@ +// Package difflib is a partial port of Python difflib module. +// +// It provides tools to compare sequences of strings and generate textual diffs. +// +// The following class and functions have been ported: +// +// - SequenceMatcher +// +// - unified_diff +// +// - context_diff +// +// Getting unified diffs was the main goal of the port. Keep in mind this code +// is mostly suitable to output text differences in a human friendly way, there +// are no guarantees generated diffs are consumable by patch(1). +package difflib + +import ( + "bufio" + "bytes" + "fmt" + "io" + "strings" +) + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func calculateRatio(matches, length int) float64 { + if length > 0 { + return 2.0 * float64(matches) / float64(length) + } + return 1.0 +} + +type Match struct { + A int + B int + Size int +} + +type OpCode struct { + Tag byte + I1 int + I2 int + J1 int + J2 int +} + +// SequenceMatcher compares sequence of strings. The basic +// algorithm predates, and is a little fancier than, an algorithm +// published in the late 1980's by Ratcliff and Obershelp under the +// hyperbolic name "gestalt pattern matching". The basic idea is to find +// the longest contiguous matching subsequence that contains no "junk" +// elements (R-O doesn't address junk). The same idea is then applied +// recursively to the pieces of the sequences to the left and to the right +// of the matching subsequence. This does not yield minimal edit +// sequences, but does tend to yield matches that "look right" to people. +// +// SequenceMatcher tries to compute a "human-friendly diff" between two +// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the +// longest *contiguous* & junk-free matching subsequence. That's what +// catches peoples' eyes. The Windows(tm) windiff has another interesting +// notion, pairing up elements that appear uniquely in each sequence. +// That, and the method here, appear to yield more intuitive difference +// reports than does diff. This method appears to be the least vulnerable +// to synching up on blocks of "junk lines", though (like blank lines in +// ordinary text files, or maybe "

" lines in HTML files). That may be +// because this is the only method of the 3 that has a *concept* of +// "junk" . +// +// Timing: Basic R-O is cubic time worst case and quadratic time expected +// case. SequenceMatcher is quadratic time for the worst case and has +// expected-case behavior dependent in a complicated way on how many +// elements the sequences have in common; best case time is linear. +type SequenceMatcher struct { + a []string + b []string + b2j map[string][]int + IsJunk func(string) bool + autoJunk bool + bJunk map[string]struct{} + matchingBlocks []Match + fullBCount map[string]int + bPopular map[string]struct{} + opCodes []OpCode +} + +func NewMatcher(a, b []string) *SequenceMatcher { + m := SequenceMatcher{autoJunk: true} + m.SetSeqs(a, b) + return &m +} + +func NewMatcherWithJunk(a, b []string, autoJunk bool, + isJunk func(string) bool) *SequenceMatcher { + + m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} + m.SetSeqs(a, b) + return &m +} + +// Set two sequences to be compared. +func (m *SequenceMatcher) SetSeqs(a, b []string) { + m.SetSeq1(a) + m.SetSeq2(b) +} + +// Set the first sequence to be compared. The second sequence to be compared is +// not changed. +// +// SequenceMatcher computes and caches detailed information about the second +// sequence, so if you want to compare one sequence S against many sequences, +// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other +// sequences. +// +// See also SetSeqs() and SetSeq2(). +func (m *SequenceMatcher) SetSeq1(a []string) { + if &a == &m.a { + return + } + m.a = a + m.matchingBlocks = nil + m.opCodes = nil +} + +// Set the second sequence to be compared. The first sequence to be compared is +// not changed. +func (m *SequenceMatcher) SetSeq2(b []string) { + if &b == &m.b { + return + } + m.b = b + m.matchingBlocks = nil + m.opCodes = nil + m.fullBCount = nil + m.chainB() +} + +func (m *SequenceMatcher) chainB() { + // Populate line -> index mapping + b2j := map[string][]int{} + for i, s := range m.b { + indices := b2j[s] + indices = append(indices, i) + b2j[s] = indices + } + + // Purge junk elements + m.bJunk = map[string]struct{}{} + if m.IsJunk != nil { + junk := m.bJunk + for s, _ := range b2j { + if m.IsJunk(s) { + junk[s] = struct{}{} + } + } + for s, _ := range junk { + delete(b2j, s) + } + } + + // Purge remaining popular elements + popular := map[string]struct{}{} + n := len(m.b) + if m.autoJunk && n >= 200 { + ntest := n/100 + 1 + for s, indices := range b2j { + if len(indices) > ntest { + popular[s] = struct{}{} + } + } + for s, _ := range popular { + delete(b2j, s) + } + } + m.bPopular = popular + m.b2j = b2j +} + +func (m *SequenceMatcher) isBJunk(s string) bool { + _, ok := m.bJunk[s] + return ok +} + +// Find longest matching block in a[alo:ahi] and b[blo:bhi]. +// +// If IsJunk is not defined: +// +// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where +// alo <= i <= i+k <= ahi +// blo <= j <= j+k <= bhi +// and for all (i',j',k') meeting those conditions, +// k >= k' +// i <= i' +// and if i == i', j <= j' +// +// In other words, of all maximal matching blocks, return one that +// starts earliest in a, and of all those maximal matching blocks that +// start earliest in a, return the one that starts earliest in b. +// +// If IsJunk is defined, first the longest matching block is +// determined as above, but with the additional restriction that no +// junk element appears in the block. Then that block is extended as +// far as possible by matching (only) junk elements on both sides. So +// the resulting block never matches on junk except as identical junk +// happens to be adjacent to an "interesting" match. +// +// If no blocks match, return (alo, blo, 0). +func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { + // CAUTION: stripping common prefix or suffix would be incorrect. + // E.g., + // ab + // acab + // Longest matching block is "ab", but if common prefix is + // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so + // strip, so ends up claiming that ab is changed to acab by + // inserting "ca" in the middle. That's minimal but unintuitive: + // "it's obvious" that someone inserted "ac" at the front. + // Windiff ends up at the same place as diff, but by pairing up + // the unique 'b's and then matching the first two 'a's. + besti, bestj, bestsize := alo, blo, 0 + + // find longest junk-free match + // during an iteration of the loop, j2len[j] = length of longest + // junk-free match ending with a[i-1] and b[j] + j2len := map[int]int{} + for i := alo; i != ahi; i++ { + // look at all instances of a[i] in b; note that because + // b2j has no junk keys, the loop is skipped if a[i] is junk + newj2len := map[int]int{} + for _, j := range m.b2j[m.a[i]] { + // a[i] matches b[j] + if j < blo { + continue + } + if j >= bhi { + break + } + k := j2len[j-1] + 1 + newj2len[j] = k + if k > bestsize { + besti, bestj, bestsize = i-k+1, j-k+1, k + } + } + j2len = newj2len + } + + // Extend the best by non-junk elements on each end. In particular, + // "popular" non-junk elements aren't in b2j, which greatly speeds + // the inner loop above, but also means "the best" match so far + // doesn't contain any junk *or* popular non-junk elements. + for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) && + m.a[besti-1] == m.b[bestj-1] { + besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 + } + for besti+bestsize < ahi && bestj+bestsize < bhi && + !m.isBJunk(m.b[bestj+bestsize]) && + m.a[besti+bestsize] == m.b[bestj+bestsize] { + bestsize += 1 + } + + // Now that we have a wholly interesting match (albeit possibly + // empty!), we may as well suck up the matching junk on each + // side of it too. Can't think of a good reason not to, and it + // saves post-processing the (possibly considerable) expense of + // figuring out what to do with it. In the case of an empty + // interesting match, this is clearly the right thing to do, + // because no other kind of match is possible in the regions. + for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) && + m.a[besti-1] == m.b[bestj-1] { + besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 + } + for besti+bestsize < ahi && bestj+bestsize < bhi && + m.isBJunk(m.b[bestj+bestsize]) && + m.a[besti+bestsize] == m.b[bestj+bestsize] { + bestsize += 1 + } + + return Match{A: besti, B: bestj, Size: bestsize} +} + +// Return list of triples describing matching subsequences. +// +// Each triple is of the form (i, j, n), and means that +// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in +// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are +// adjacent triples in the list, and the second is not the last triple in the +// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe +// adjacent equal blocks. +// +// The last triple is a dummy, (len(a), len(b), 0), and is the only +// triple with n==0. +func (m *SequenceMatcher) GetMatchingBlocks() []Match { + if m.matchingBlocks != nil { + return m.matchingBlocks + } + + var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match + matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match { + match := m.findLongestMatch(alo, ahi, blo, bhi) + i, j, k := match.A, match.B, match.Size + if match.Size > 0 { + if alo < i && blo < j { + matched = matchBlocks(alo, i, blo, j, matched) + } + matched = append(matched, match) + if i+k < ahi && j+k < bhi { + matched = matchBlocks(i+k, ahi, j+k, bhi, matched) + } + } + return matched + } + matched := matchBlocks(0, len(m.a), 0, len(m.b), nil) + + // It's possible that we have adjacent equal blocks in the + // matching_blocks list now. + nonAdjacent := []Match{} + i1, j1, k1 := 0, 0, 0 + for _, b := range matched { + // Is this block adjacent to i1, j1, k1? + i2, j2, k2 := b.A, b.B, b.Size + if i1+k1 == i2 && j1+k1 == j2 { + // Yes, so collapse them -- this just increases the length of + // the first block by the length of the second, and the first + // block so lengthened remains the block to compare against. + k1 += k2 + } else { + // Not adjacent. Remember the first block (k1==0 means it's + // the dummy we started with), and make the second block the + // new block to compare against. + if k1 > 0 { + nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) + } + i1, j1, k1 = i2, j2, k2 + } + } + if k1 > 0 { + nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) + } + + nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0}) + m.matchingBlocks = nonAdjacent + return m.matchingBlocks +} + +// Return list of 5-tuples describing how to turn a into b. +// +// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple +// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the +// tuple preceding it, and likewise for j1 == the previous j2. +// +// The tags are characters, with these meanings: +// +// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2] +// +// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case. +// +// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case. +// +// 'e' (equal): a[i1:i2] == b[j1:j2] +func (m *SequenceMatcher) GetOpCodes() []OpCode { + if m.opCodes != nil { + return m.opCodes + } + i, j := 0, 0 + matching := m.GetMatchingBlocks() + opCodes := make([]OpCode, 0, len(matching)) + for _, m := range matching { + // invariant: we've pumped out correct diffs to change + // a[:i] into b[:j], and the next matching block is + // a[ai:ai+size] == b[bj:bj+size]. So we need to pump + // out a diff to change a[i:ai] into b[j:bj], pump out + // the matching block, and move (i,j) beyond the match + ai, bj, size := m.A, m.B, m.Size + tag := byte(0) + if i < ai && j < bj { + tag = 'r' + } else if i < ai { + tag = 'd' + } else if j < bj { + tag = 'i' + } + if tag > 0 { + opCodes = append(opCodes, OpCode{tag, i, ai, j, bj}) + } + i, j = ai+size, bj+size + // the list of matching blocks is terminated by a + // sentinel with size 0 + if size > 0 { + opCodes = append(opCodes, OpCode{'e', ai, i, bj, j}) + } + } + m.opCodes = opCodes + return m.opCodes +} + +// Isolate change clusters by eliminating ranges with no changes. +// +// Return a generator of groups with up to n lines of context. +// Each group is in the same format as returned by GetOpCodes(). +func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { + if n < 0 { + n = 3 + } + codes := m.GetOpCodes() + if len(codes) == 0 { + codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} + } + // Fixup leading and trailing groups if they show no changes. + if codes[0].Tag == 'e' { + c := codes[0] + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} + } + if codes[len(codes)-1].Tag == 'e' { + c := codes[len(codes)-1] + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} + } + nn := n + n + groups := [][]OpCode{} + group := []OpCode{} + for _, c := range codes { + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + // End the current group and start a new one whenever + // there is a large range with no changes. + if c.Tag == 'e' && i2-i1 > nn { + group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), + j1, min(j2, j1+n)}) + groups = append(groups, group) + group = []OpCode{} + i1, j1 = max(i1, i2-n), max(j1, j2-n) + } + group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) + } + if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') { + groups = append(groups, group) + } + return groups +} + +// Return a measure of the sequences' similarity (float in [0,1]). +// +// Where T is the total number of elements in both sequences, and +// M is the number of matches, this is 2.0*M / T. +// Note that this is 1 if the sequences are identical, and 0 if +// they have nothing in common. +// +// .Ratio() is expensive to compute if you haven't already computed +// .GetMatchingBlocks() or .GetOpCodes(), in which case you may +// want to try .QuickRatio() or .RealQuickRation() first to get an +// upper bound. +func (m *SequenceMatcher) Ratio() float64 { + matches := 0 + for _, m := range m.GetMatchingBlocks() { + matches += m.Size + } + return calculateRatio(matches, len(m.a)+len(m.b)) +} + +// Return an upper bound on ratio() relatively quickly. +// +// This isn't defined beyond that it is an upper bound on .Ratio(), and +// is faster to compute. +func (m *SequenceMatcher) QuickRatio() float64 { + // viewing a and b as multisets, set matches to the cardinality + // of their intersection; this counts the number of matches + // without regard to order, so is clearly an upper bound + if m.fullBCount == nil { + m.fullBCount = map[string]int{} + for _, s := range m.b { + m.fullBCount[s] = m.fullBCount[s] + 1 + } + } + + // avail[x] is the number of times x appears in 'b' less the + // number of times we've seen it in 'a' so far ... kinda + avail := map[string]int{} + matches := 0 + for _, s := range m.a { + n, ok := avail[s] + if !ok { + n = m.fullBCount[s] + } + avail[s] = n - 1 + if n > 0 { + matches += 1 + } + } + return calculateRatio(matches, len(m.a)+len(m.b)) +} + +// Return an upper bound on ratio() very quickly. +// +// This isn't defined beyond that it is an upper bound on .Ratio(), and +// is faster to compute than either .Ratio() or .QuickRatio(). +func (m *SequenceMatcher) RealQuickRatio() float64 { + la, lb := len(m.a), len(m.b) + return calculateRatio(min(la, lb), la+lb) +} + +// Convert range to the "ed" format +func formatRangeUnified(start, stop int) string { + // Per the diff spec at http://www.unix.org/single_unix_specification/ + beginning := start + 1 // lines start numbering with one + length := stop - start + if length == 1 { + return fmt.Sprintf("%d", beginning) + } + if length == 0 { + beginning -= 1 // empty ranges begin at line just before the range + } + return fmt.Sprintf("%d,%d", beginning, length) +} + +// Unified diff parameters +type UnifiedDiff struct { + A []string // First sequence lines + FromFile string // First file name + FromDate string // First file time + B []string // Second sequence lines + ToFile string // Second file name + ToDate string // Second file time + Eol string // Headers end of line, defaults to LF + Context int // Number of context lines +} + +// Compare two sequences of lines; generate the delta as a unified diff. +// +// Unified diffs are a compact way of showing line changes and a few +// lines of context. The number of context lines is set by 'n' which +// defaults to three. +// +// By default, the diff control lines (those with ---, +++, or @@) are +// created with a trailing newline. This is helpful so that inputs +// created from file.readlines() result in diffs that are suitable for +// file.writelines() since both the inputs and outputs have trailing +// newlines. +// +// For inputs that do not have trailing newlines, set the lineterm +// argument to "" so that the output will be uniformly newline free. +// +// The unidiff format normally has a header for filenames and modification +// times. Any or all of these may be specified using strings for +// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. +// The modification times are normally expressed in the ISO 8601 format. +func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { + buf := bufio.NewWriter(writer) + defer buf.Flush() + wf := func(format string, args ...interface{}) error { + _, err := buf.WriteString(fmt.Sprintf(format, args...)) + return err + } + ws := func(s string) error { + _, err := buf.WriteString(s) + return err + } + + if len(diff.Eol) == 0 { + diff.Eol = "\n" + } + + started := false + m := NewMatcher(diff.A, diff.B) + for _, g := range m.GetGroupedOpCodes(diff.Context) { + if !started { + started = true + fromDate := "" + if len(diff.FromDate) > 0 { + fromDate = "\t" + diff.FromDate + } + toDate := "" + if len(diff.ToDate) > 0 { + toDate = "\t" + diff.ToDate + } + if diff.FromFile != "" || diff.ToFile != "" { + err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol) + if err != nil { + return err + } + err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol) + if err != nil { + return err + } + } + } + first, last := g[0], g[len(g)-1] + range1 := formatRangeUnified(first.I1, last.I2) + range2 := formatRangeUnified(first.J1, last.J2) + if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil { + return err + } + for _, c := range g { + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + if c.Tag == 'e' { + for _, line := range diff.A[i1:i2] { + if err := ws(" " + line); err != nil { + return err + } + } + continue + } + if c.Tag == 'r' || c.Tag == 'd' { + for _, line := range diff.A[i1:i2] { + if err := ws("-" + line); err != nil { + return err + } + } + } + if c.Tag == 'r' || c.Tag == 'i' { + for _, line := range diff.B[j1:j2] { + if err := ws("+" + line); err != nil { + return err + } + } + } + } + } + return nil +} + +// Like WriteUnifiedDiff but returns the diff a string. +func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { + w := &bytes.Buffer{} + err := WriteUnifiedDiff(w, diff) + return string(w.Bytes()), err +} + +// Convert range to the "ed" format. +func formatRangeContext(start, stop int) string { + // Per the diff spec at http://www.unix.org/single_unix_specification/ + beginning := start + 1 // lines start numbering with one + length := stop - start + if length == 0 { + beginning -= 1 // empty ranges begin at line just before the range + } + if length <= 1 { + return fmt.Sprintf("%d", beginning) + } + return fmt.Sprintf("%d,%d", beginning, beginning+length-1) +} + +type ContextDiff UnifiedDiff + +// Compare two sequences of lines; generate the delta as a context diff. +// +// Context diffs are a compact way of showing line changes and a few +// lines of context. The number of context lines is set by diff.Context +// which defaults to three. +// +// By default, the diff control lines (those with *** or ---) are +// created with a trailing newline. +// +// For inputs that do not have trailing newlines, set the diff.Eol +// argument to "" so that the output will be uniformly newline free. +// +// The context diff format normally has a header for filenames and +// modification times. Any or all of these may be specified using +// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate. +// The modification times are normally expressed in the ISO 8601 format. +// If not specified, the strings default to blanks. +func WriteContextDiff(writer io.Writer, diff ContextDiff) error { + buf := bufio.NewWriter(writer) + defer buf.Flush() + var diffErr error + wf := func(format string, args ...interface{}) { + _, err := buf.WriteString(fmt.Sprintf(format, args...)) + if diffErr == nil && err != nil { + diffErr = err + } + } + ws := func(s string) { + _, err := buf.WriteString(s) + if diffErr == nil && err != nil { + diffErr = err + } + } + + if len(diff.Eol) == 0 { + diff.Eol = "\n" + } + + prefix := map[byte]string{ + 'i': "+ ", + 'd': "- ", + 'r': "! ", + 'e': " ", + } + + started := false + m := NewMatcher(diff.A, diff.B) + for _, g := range m.GetGroupedOpCodes(diff.Context) { + if !started { + started = true + fromDate := "" + if len(diff.FromDate) > 0 { + fromDate = "\t" + diff.FromDate + } + toDate := "" + if len(diff.ToDate) > 0 { + toDate = "\t" + diff.ToDate + } + if diff.FromFile != "" || diff.ToFile != "" { + wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol) + wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol) + } + } + + first, last := g[0], g[len(g)-1] + ws("***************" + diff.Eol) + + range1 := formatRangeContext(first.I1, last.I2) + wf("*** %s ****%s", range1, diff.Eol) + for _, c := range g { + if c.Tag == 'r' || c.Tag == 'd' { + for _, cc := range g { + if cc.Tag == 'i' { + continue + } + for _, line := range diff.A[cc.I1:cc.I2] { + ws(prefix[cc.Tag] + line) + } + } + break + } + } + + range2 := formatRangeContext(first.J1, last.J2) + wf("--- %s ----%s", range2, diff.Eol) + for _, c := range g { + if c.Tag == 'r' || c.Tag == 'i' { + for _, cc := range g { + if cc.Tag == 'd' { + continue + } + for _, line := range diff.B[cc.J1:cc.J2] { + ws(prefix[cc.Tag] + line) + } + } + break + } + } + } + return diffErr +} + +// Like WriteContextDiff but returns the diff a string. +func GetContextDiffString(diff ContextDiff) (string, error) { + w := &bytes.Buffer{} + err := WriteContextDiff(w, diff) + return string(w.Bytes()), err +} + +// Split a string on "\n" while preserving them. The output can be used +// as input for UnifiedDiff and ContextDiff structures. +func SplitLines(s string) []string { + lines := strings.SplitAfter(s, "\n") + lines[len(lines)-1] += "\n" + return lines +} diff --git a/vendor/github.com/stretchr/testify/LICENSE b/vendor/github.com/stretchr/testify/LICENSE new file mode 100644 index 00000000..473b670a --- /dev/null +++ b/vendor/github.com/stretchr/testify/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell + +Please consider promoting this project if you find it useful. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT +OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go b/vendor/github.com/stretchr/testify/assert/assertion_format.go new file mode 100644 index 00000000..aa1c2b95 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertion_format.go @@ -0,0 +1,484 @@ +/* +* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen +* THIS FILE MUST NOT BE EDITED BY HAND + */ + +package assert + +import ( + http "net/http" + url "net/url" + time "time" +) + +// Conditionf uses a Comparison to assert a complex condition. +func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Condition(t, comp, append([]interface{}{msg}, args...)...) +} + +// Containsf asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") +// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") +// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") +func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Contains(t, s, contains, append([]interface{}{msg}, args...)...) +} + +// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. +func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return DirExists(t, path, append([]interface{}{msg}, args...)...) +} + +// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") +func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return ElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...) +} + +// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Emptyf(t, obj, "error message %s", "formatted") +func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Empty(t, object, append([]interface{}{msg}, args...)...) +} + +// Equalf asserts that two objects are equal. +// +// assert.Equalf(t, 123, 123, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Equal(t, expected, actual, append([]interface{}{msg}, args...)...) +} + +// EqualErrorf asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") +func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...) +} + +// EqualValuesf asserts that two objects are equal or convertable to the same types +// and equal. +// +// assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) +func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) +} + +// Errorf asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Errorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } +func Errorf(t TestingT, err error, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Error(t, err, append([]interface{}{msg}, args...)...) +} + +// Exactlyf asserts that two objects are equal in value and type. +// +// assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) +func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Exactly(t, expected, actual, append([]interface{}{msg}, args...)...) +} + +// Failf reports a failure through +func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Fail(t, failureMessage, append([]interface{}{msg}, args...)...) +} + +// FailNowf fails test +func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return FailNow(t, failureMessage, append([]interface{}{msg}, args...)...) +} + +// Falsef asserts that the specified value is false. +// +// assert.Falsef(t, myBool, "error message %s", "formatted") +func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return False(t, value, append([]interface{}{msg}, args...)...) +} + +// FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. +func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return FileExists(t, path, append([]interface{}{msg}, args...)...) +} + +// HTTPBodyContainsf asserts that a specified handler returns a +// body that contains a string. +// +// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return HTTPBodyContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) +} + +// HTTPBodyNotContainsf asserts that a specified handler returns a +// body that does not contain a string. +// +// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return HTTPBodyNotContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) +} + +// HTTPErrorf asserts that a specified handler returns an error status code. +// +// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return HTTPError(t, handler, method, url, values, append([]interface{}{msg}, args...)...) +} + +// HTTPRedirectf asserts that a specified handler returns a redirect status code. +// +// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return HTTPRedirect(t, handler, method, url, values, append([]interface{}{msg}, args...)...) +} + +// HTTPSuccessf asserts that a specified handler returns a success status code. +// +// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return HTTPSuccess(t, handler, method, url, values, append([]interface{}{msg}, args...)...) +} + +// Implementsf asserts that an object is implemented by the specified interface. +// +// assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) +func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Implements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) +} + +// InDeltaf asserts that the two numerals are within delta of each other. +// +// assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) +func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return InDelta(t, expected, actual, delta, append([]interface{}{msg}, args...)...) +} + +// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return InDeltaMapValues(t, expected, actual, delta, append([]interface{}{msg}, args...)...) +} + +// InDeltaSlicef is the same as InDelta, except it compares two slices. +func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return InDeltaSlice(t, expected, actual, delta, append([]interface{}{msg}, args...)...) +} + +// InEpsilonf asserts that expected and actual have a relative error less than epsilon +func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) +} + +// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. +func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return InEpsilonSlice(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) +} + +// IsTypef asserts that the specified objects are of the same type. +func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return IsType(t, expectedType, object, append([]interface{}{msg}, args...)...) +} + +// JSONEqf asserts that two JSON strings are equivalent. +// +// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return JSONEq(t, expected, actual, append([]interface{}{msg}, args...)...) +} + +// Lenf asserts that the specified object has specific length. +// Lenf also fails if the object has a type that len() not accept. +// +// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") +func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Len(t, object, length, append([]interface{}{msg}, args...)...) +} + +// Nilf asserts that the specified object is nil. +// +// assert.Nilf(t, err, "error message %s", "formatted") +func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Nil(t, object, append([]interface{}{msg}, args...)...) +} + +// NoErrorf asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if assert.NoErrorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } +func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NoError(t, err, append([]interface{}{msg}, args...)...) +} + +// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") +func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotContains(t, s, contains, append([]interface{}{msg}, args...)...) +} + +// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } +func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotEmpty(t, object, append([]interface{}{msg}, args...)...) +} + +// NotEqualf asserts that the specified values are NOT equal. +// +// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...) +} + +// NotNilf asserts that the specified object is not nil. +// +// assert.NotNilf(t, err, "error message %s", "formatted") +func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotNil(t, object, append([]interface{}{msg}, args...)...) +} + +// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") +func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotPanics(t, f, append([]interface{}{msg}, args...)...) +} + +// NotRegexpf asserts that a specified regexp does not match a string. +// +// assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") +// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") +func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotRegexp(t, rx, str, append([]interface{}{msg}, args...)...) +} + +// NotSubsetf asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotSubset(t, list, subset, append([]interface{}{msg}, args...)...) +} + +// NotZerof asserts that i is not the zero value for its type. +func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotZero(t, i, append([]interface{}{msg}, args...)...) +} + +// Panicsf asserts that the code inside the specified PanicTestFunc panics. +// +// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") +func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Panics(t, f, append([]interface{}{msg}, args...)...) +} + +// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return PanicsWithValue(t, expected, f, append([]interface{}{msg}, args...)...) +} + +// Regexpf asserts that a specified regexp matches a string. +// +// assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") +// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") +func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Regexp(t, rx, str, append([]interface{}{msg}, args...)...) +} + +// Subsetf asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Subset(t, list, subset, append([]interface{}{msg}, args...)...) +} + +// Truef asserts that the specified value is true. +// +// assert.Truef(t, myBool, "error message %s", "formatted") +func Truef(t TestingT, value bool, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return True(t, value, append([]interface{}{msg}, args...)...) +} + +// WithinDurationf asserts that the two times are within duration delta of each other. +// +// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...) +} + +// Zerof asserts that i is the zero value for its type. +func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return Zero(t, i, append([]interface{}{msg}, args...)...) +} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl new file mode 100644 index 00000000..d2bb0b81 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl @@ -0,0 +1,5 @@ +{{.CommentFormat}} +func {{.DocInfo.Name}}f(t TestingT, {{.ParamsFormat}}) bool { + if h, ok := t.(tHelper); ok { h.Helper() } + return {{.DocInfo.Name}}(t, {{.ForwardedParamsFormat}}) +} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go new file mode 100644 index 00000000..de39f794 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go @@ -0,0 +1,956 @@ +/* +* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen +* THIS FILE MUST NOT BE EDITED BY HAND + */ + +package assert + +import ( + http "net/http" + url "net/url" + time "time" +) + +// Condition uses a Comparison to assert a complex condition. +func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Condition(a.t, comp, msgAndArgs...) +} + +// Conditionf uses a Comparison to assert a complex condition. +func (a *Assertions) Conditionf(comp Comparison, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Conditionf(a.t, comp, msg, args...) +} + +// Contains asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// a.Contains("Hello World", "World") +// a.Contains(["Hello", "World"], "World") +// a.Contains({"Hello": "World"}, "Hello") +func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Contains(a.t, s, contains, msgAndArgs...) +} + +// Containsf asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// a.Containsf("Hello World", "World", "error message %s", "formatted") +// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") +// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") +func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Containsf(a.t, s, contains, msg, args...) +} + +// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. +func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return DirExists(a.t, path, msgAndArgs...) +} + +// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. +func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return DirExistsf(a.t, path, msg, args...) +} + +// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) +func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return ElementsMatch(a.t, listA, listB, msgAndArgs...) +} + +// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") +func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return ElementsMatchf(a.t, listA, listB, msg, args...) +} + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// a.Empty(obj) +func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Empty(a.t, object, msgAndArgs...) +} + +// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// a.Emptyf(obj, "error message %s", "formatted") +func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Emptyf(a.t, object, msg, args...) +} + +// Equal asserts that two objects are equal. +// +// a.Equal(123, 123) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Equal(a.t, expected, actual, msgAndArgs...) +} + +// EqualError asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// a.EqualError(err, expectedErrorString) +func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return EqualError(a.t, theError, errString, msgAndArgs...) +} + +// EqualErrorf asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") +func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return EqualErrorf(a.t, theError, errString, msg, args...) +} + +// EqualValues asserts that two objects are equal or convertable to the same types +// and equal. +// +// a.EqualValues(uint32(123), int32(123)) +func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return EqualValues(a.t, expected, actual, msgAndArgs...) +} + +// EqualValuesf asserts that two objects are equal or convertable to the same types +// and equal. +// +// a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) +func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return EqualValuesf(a.t, expected, actual, msg, args...) +} + +// Equalf asserts that two objects are equal. +// +// a.Equalf(123, 123, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Equalf(a.t, expected, actual, msg, args...) +} + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if a.Error(err) { +// assert.Equal(t, expectedError, err) +// } +func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Error(a.t, err, msgAndArgs...) +} + +// Errorf asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if a.Errorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } +func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Errorf(a.t, err, msg, args...) +} + +// Exactly asserts that two objects are equal in value and type. +// +// a.Exactly(int32(123), int64(123)) +func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Exactly(a.t, expected, actual, msgAndArgs...) +} + +// Exactlyf asserts that two objects are equal in value and type. +// +// a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) +func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Exactlyf(a.t, expected, actual, msg, args...) +} + +// Fail reports a failure through +func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Fail(a.t, failureMessage, msgAndArgs...) +} + +// FailNow fails test +func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return FailNow(a.t, failureMessage, msgAndArgs...) +} + +// FailNowf fails test +func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return FailNowf(a.t, failureMessage, msg, args...) +} + +// Failf reports a failure through +func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Failf(a.t, failureMessage, msg, args...) +} + +// False asserts that the specified value is false. +// +// a.False(myBool) +func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return False(a.t, value, msgAndArgs...) +} + +// Falsef asserts that the specified value is false. +// +// a.Falsef(myBool, "error message %s", "formatted") +func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Falsef(a.t, value, msg, args...) +} + +// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. +func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return FileExists(a.t, path, msgAndArgs...) +} + +// FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. +func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return FileExistsf(a.t, path, msg, args...) +} + +// HTTPBodyContains asserts that a specified handler returns a +// body that contains a string. +// +// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...) +} + +// HTTPBodyContainsf asserts that a specified handler returns a +// body that contains a string. +// +// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...) +} + +// HTTPBodyNotContains asserts that a specified handler returns a +// body that does not contain a string. +// +// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...) +} + +// HTTPBodyNotContainsf asserts that a specified handler returns a +// body that does not contain a string. +// +// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...) +} + +// HTTPError asserts that a specified handler returns an error status code. +// +// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPError(a.t, handler, method, url, values, msgAndArgs...) +} + +// HTTPErrorf asserts that a specified handler returns an error status code. +// +// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPErrorf(a.t, handler, method, url, values, msg, args...) +} + +// HTTPRedirect asserts that a specified handler returns a redirect status code. +// +// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...) +} + +// HTTPRedirectf asserts that a specified handler returns a redirect status code. +// +// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPRedirectf(a.t, handler, method, url, values, msg, args...) +} + +// HTTPSuccess asserts that a specified handler returns a success status code. +// +// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...) +} + +// HTTPSuccessf asserts that a specified handler returns a success status code. +// +// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPSuccessf(a.t, handler, method, url, values, msg, args...) +} + +// Implements asserts that an object is implemented by the specified interface. +// +// a.Implements((*MyInterface)(nil), new(MyObject)) +func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Implements(a.t, interfaceObject, object, msgAndArgs...) +} + +// Implementsf asserts that an object is implemented by the specified interface. +// +// a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) +func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Implementsf(a.t, interfaceObject, object, msg, args...) +} + +// InDelta asserts that the two numerals are within delta of each other. +// +// a.InDelta(math.Pi, (22 / 7.0), 0.01) +func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return InDelta(a.t, expected, actual, delta, msgAndArgs...) +} + +// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...) +} + +// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...) +} + +// InDeltaSlice is the same as InDelta, except it compares two slices. +func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) +} + +// InDeltaSlicef is the same as InDelta, except it compares two slices. +func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return InDeltaSlicef(a.t, expected, actual, delta, msg, args...) +} + +// InDeltaf asserts that the two numerals are within delta of each other. +// +// a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) +func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return InDeltaf(a.t, expected, actual, delta, msg, args...) +} + +// InEpsilon asserts that expected and actual have a relative error less than epsilon +func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) +} + +// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. +func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) +} + +// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. +func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) +} + +// InEpsilonf asserts that expected and actual have a relative error less than epsilon +func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return InEpsilonf(a.t, expected, actual, epsilon, msg, args...) +} + +// IsType asserts that the specified objects are of the same type. +func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return IsType(a.t, expectedType, object, msgAndArgs...) +} + +// IsTypef asserts that the specified objects are of the same type. +func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return IsTypef(a.t, expectedType, object, msg, args...) +} + +// JSONEq asserts that two JSON strings are equivalent. +// +// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return JSONEq(a.t, expected, actual, msgAndArgs...) +} + +// JSONEqf asserts that two JSON strings are equivalent. +// +// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return JSONEqf(a.t, expected, actual, msg, args...) +} + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// a.Len(mySlice, 3) +func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Len(a.t, object, length, msgAndArgs...) +} + +// Lenf asserts that the specified object has specific length. +// Lenf also fails if the object has a type that len() not accept. +// +// a.Lenf(mySlice, 3, "error message %s", "formatted") +func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Lenf(a.t, object, length, msg, args...) +} + +// Nil asserts that the specified object is nil. +// +// a.Nil(err) +func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Nil(a.t, object, msgAndArgs...) +} + +// Nilf asserts that the specified object is nil. +// +// a.Nilf(err, "error message %s", "formatted") +func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Nilf(a.t, object, msg, args...) +} + +// NoError asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if a.NoError(err) { +// assert.Equal(t, expectedObj, actualObj) +// } +func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NoError(a.t, err, msgAndArgs...) +} + +// NoErrorf asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if a.NoErrorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } +func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NoErrorf(a.t, err, msg, args...) +} + +// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// a.NotContains("Hello World", "Earth") +// a.NotContains(["Hello", "World"], "Earth") +// a.NotContains({"Hello": "World"}, "Earth") +func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotContains(a.t, s, contains, msgAndArgs...) +} + +// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") +// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") +// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") +func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotContainsf(a.t, s, contains, msg, args...) +} + +// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if a.NotEmpty(obj) { +// assert.Equal(t, "two", obj[1]) +// } +func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotEmpty(a.t, object, msgAndArgs...) +} + +// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if a.NotEmptyf(obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } +func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotEmptyf(a.t, object, msg, args...) +} + +// NotEqual asserts that the specified values are NOT equal. +// +// a.NotEqual(obj1, obj2) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotEqual(a.t, expected, actual, msgAndArgs...) +} + +// NotEqualf asserts that the specified values are NOT equal. +// +// a.NotEqualf(obj1, obj2, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotEqualf(a.t, expected, actual, msg, args...) +} + +// NotNil asserts that the specified object is not nil. +// +// a.NotNil(err) +func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotNil(a.t, object, msgAndArgs...) +} + +// NotNilf asserts that the specified object is not nil. +// +// a.NotNilf(err, "error message %s", "formatted") +func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotNilf(a.t, object, msg, args...) +} + +// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// a.NotPanics(func(){ RemainCalm() }) +func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotPanics(a.t, f, msgAndArgs...) +} + +// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") +func (a *Assertions) NotPanicsf(f PanicTestFunc, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotPanicsf(a.t, f, msg, args...) +} + +// NotRegexp asserts that a specified regexp does not match a string. +// +// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") +// a.NotRegexp("^start", "it's not starting") +func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotRegexp(a.t, rx, str, msgAndArgs...) +} + +// NotRegexpf asserts that a specified regexp does not match a string. +// +// a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") +// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") +func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotRegexpf(a.t, rx, str, msg, args...) +} + +// NotSubset asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotSubset(a.t, list, subset, msgAndArgs...) +} + +// NotSubsetf asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotSubsetf(a.t, list, subset, msg, args...) +} + +// NotZero asserts that i is not the zero value for its type. +func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotZero(a.t, i, msgAndArgs...) +} + +// NotZerof asserts that i is not the zero value for its type. +func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotZerof(a.t, i, msg, args...) +} + +// Panics asserts that the code inside the specified PanicTestFunc panics. +// +// a.Panics(func(){ GoCrazy() }) +func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Panics(a.t, f, msgAndArgs...) +} + +// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) +func (a *Assertions) PanicsWithValue(expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return PanicsWithValue(a.t, expected, f, msgAndArgs...) +} + +// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +func (a *Assertions) PanicsWithValuef(expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return PanicsWithValuef(a.t, expected, f, msg, args...) +} + +// Panicsf asserts that the code inside the specified PanicTestFunc panics. +// +// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") +func (a *Assertions) Panicsf(f PanicTestFunc, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Panicsf(a.t, f, msg, args...) +} + +// Regexp asserts that a specified regexp matches a string. +// +// a.Regexp(regexp.MustCompile("start"), "it's starting") +// a.Regexp("start...$", "it's not starting") +func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Regexp(a.t, rx, str, msgAndArgs...) +} + +// Regexpf asserts that a specified regexp matches a string. +// +// a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") +// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") +func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Regexpf(a.t, rx, str, msg, args...) +} + +// Subset asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Subset(a.t, list, subset, msgAndArgs...) +} + +// Subsetf asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Subsetf(a.t, list, subset, msg, args...) +} + +// True asserts that the specified value is true. +// +// a.True(myBool) +func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return True(a.t, value, msgAndArgs...) +} + +// Truef asserts that the specified value is true. +// +// a.Truef(myBool, "error message %s", "formatted") +func (a *Assertions) Truef(value bool, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Truef(a.t, value, msg, args...) +} + +// WithinDuration asserts that the two times are within duration delta of each other. +// +// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) +func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) +} + +// WithinDurationf asserts that the two times are within duration delta of each other. +// +// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return WithinDurationf(a.t, expected, actual, delta, msg, args...) +} + +// Zero asserts that i is the zero value for its type. +func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Zero(a.t, i, msgAndArgs...) +} + +// Zerof asserts that i is the zero value for its type. +func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return Zerof(a.t, i, msg, args...) +} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl new file mode 100644 index 00000000..188bb9e1 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl @@ -0,0 +1,5 @@ +{{.CommentWithoutT "a"}} +func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool { + if h, ok := a.t.(tHelper); ok { h.Helper() } + return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) +} diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go new file mode 100644 index 00000000..5bdec56c --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertions.go @@ -0,0 +1,1394 @@ +package assert + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "fmt" + "math" + "os" + "reflect" + "regexp" + "runtime" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/davecgh/go-spew/spew" + "github.com/pmezard/go-difflib/difflib" +) + +//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_format.go.tmpl + +// TestingT is an interface wrapper around *testing.T +type TestingT interface { + Errorf(format string, args ...interface{}) +} + +// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful +// for table driven tests. +type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool + +// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful +// for table driven tests. +type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool + +// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful +// for table driven tests. +type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool + +// ValuesAssertionFunc is a common function prototype when validating an error value. Can be useful +// for table driven tests. +type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool + +// Comparison a custom function that returns true on success and false on failure +type Comparison func() (success bool) + +/* + Helper functions +*/ + +// ObjectsAreEqual determines if two objects are considered equal. +// +// This function does no assertion of any kind. +func ObjectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} + +// ObjectsAreEqualValues gets whether two objects are equal, or if their +// values are equal. +func ObjectsAreEqualValues(expected, actual interface{}) bool { + if ObjectsAreEqual(expected, actual) { + return true + } + + actualType := reflect.TypeOf(actual) + if actualType == nil { + return false + } + expectedValue := reflect.ValueOf(expected) + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + // Attempt comparison after type conversion + return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + + return false +} + +/* CallerInfo is necessary because the assert functions use the testing object +internally, causing it to print the file:line of the assert method, rather than where +the problem actually occurred in calling code.*/ + +// CallerInfo returns an array of strings containing the file and line number +// of each stack frame leading from the current test to the assert call that +// failed. +func CallerInfo() []string { + + pc := uintptr(0) + file := "" + line := 0 + ok := false + name := "" + + callers := []string{} + for i := 0; ; i++ { + pc, file, line, ok = runtime.Caller(i) + if !ok { + // The breaks below failed to terminate the loop, and we ran off the + // end of the call stack. + break + } + + // This is a huge edge case, but it will panic if this is the case, see #180 + if file == "" { + break + } + + f := runtime.FuncForPC(pc) + if f == nil { + break + } + name = f.Name() + + // testing.tRunner is the standard library function that calls + // tests. Subtests are called directly by tRunner, without going through + // the Test/Benchmark/Example function that contains the t.Run calls, so + // with subtests we should break when we hit tRunner, without adding it + // to the list of callers. + if name == "testing.tRunner" { + break + } + + parts := strings.Split(file, "/") + file = parts[len(parts)-1] + if len(parts) > 1 { + dir := parts[len(parts)-2] + if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { + callers = append(callers, fmt.Sprintf("%s:%d", file, line)) + } + } + + // Drop the package + segments := strings.Split(name, ".") + name = segments[len(segments)-1] + if isTest(name, "Test") || + isTest(name, "Benchmark") || + isTest(name, "Example") { + break + } + } + + return callers +} + +// Stolen from the `go test` tool. +// isTest tells whether name looks like a test (or benchmark, according to prefix). +// It is a Test (say) if there is a character after Test that is not a lower-case letter. +// We don't want TesticularCancer. +func isTest(name, prefix string) bool { + if !strings.HasPrefix(name, prefix) { + return false + } + if len(name) == len(prefix) { // "Test" is ok + return true + } + rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) + return !unicode.IsLower(rune) +} + +func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { + if len(msgAndArgs) == 0 || msgAndArgs == nil { + return "" + } + if len(msgAndArgs) == 1 { + return msgAndArgs[0].(string) + } + if len(msgAndArgs) > 1 { + return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) + } + return "" +} + +// Aligns the provided message so that all lines after the first line start at the same location as the first line. +// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). +// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the +// basis on which the alignment occurs). +func indentMessageLines(message string, longestLabelLen int) string { + outBuf := new(bytes.Buffer) + + for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { + // no need to align first line because it starts at the correct location (after the label) + if i != 0 { + // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab + outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t") + } + outBuf.WriteString(scanner.Text()) + } + + return outBuf.String() +} + +type failNower interface { + FailNow() +} + +// FailNow fails test +func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + Fail(t, failureMessage, msgAndArgs...) + + // We cannot extend TestingT with FailNow() and + // maintain backwards compatibility, so we fallback + // to panicking when FailNow is not available in + // TestingT. + // See issue #263 + + if t, ok := t.(failNower); ok { + t.FailNow() + } else { + panic("test failed and t is missing `FailNow()`") + } + return false +} + +// Fail reports a failure through +func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + content := []labeledContent{ + {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")}, + {"Error", failureMessage}, + } + + // Add test name if the Go version supports it + if n, ok := t.(interface { + Name() string + }); ok { + content = append(content, labeledContent{"Test", n.Name()}) + } + + message := messageFromMsgAndArgs(msgAndArgs...) + if len(message) > 0 { + content = append(content, labeledContent{"Messages", message}) + } + + t.Errorf("\n%s", ""+labeledOutput(content...)) + + return false +} + +type labeledContent struct { + label string + content string +} + +// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: +// +// \t{{label}}:{{align_spaces}}\t{{content}}\n +// +// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. +// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this +// alignment is achieved, "\t{{content}}\n" is added for the output. +// +// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line. +func labeledOutput(content ...labeledContent) string { + longestLabel := 0 + for _, v := range content { + if len(v.label) > longestLabel { + longestLabel = len(v.label) + } + } + var output string + for _, v := range content { + output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n" + } + return output +} + +// Implements asserts that an object is implemented by the specified interface. +// +// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) +func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + interfaceType := reflect.TypeOf(interfaceObject).Elem() + + if object == nil { + return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...) + } + if !reflect.TypeOf(object).Implements(interfaceType) { + return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) + } + + return true +} + +// IsType asserts that the specified objects are of the same type. +func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { + return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) + } + + return true +} + +// Equal asserts that two objects are equal. +// +// assert.Equal(t, 123, 123) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if err := validateEqualArgs(expected, actual); err != nil { + return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)", + expected, actual, err), msgAndArgs...) + } + + if !ObjectsAreEqual(expected, actual) { + diff := diff(expected, actual) + expected, actual = formatUnequalValues(expected, actual) + return Fail(t, fmt.Sprintf("Not equal: \n"+ + "expected: %s\n"+ + "actual : %s%s", expected, actual, diff), msgAndArgs...) + } + + return true + +} + +// formatUnequalValues takes two values of arbitrary types and returns string +// representations appropriate to be presented to the user. +// +// If the values are not of like type, the returned strings will be prefixed +// with the type name, and the value will be enclosed in parenthesis similar +// to a type conversion in the Go grammar. +func formatUnequalValues(expected, actual interface{}) (e string, a string) { + if reflect.TypeOf(expected) != reflect.TypeOf(actual) { + return fmt.Sprintf("%T(%#v)", expected, expected), + fmt.Sprintf("%T(%#v)", actual, actual) + } + + return fmt.Sprintf("%#v", expected), + fmt.Sprintf("%#v", actual) +} + +// EqualValues asserts that two objects are equal or convertable to the same types +// and equal. +// +// assert.EqualValues(t, uint32(123), int32(123)) +func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + if !ObjectsAreEqualValues(expected, actual) { + diff := diff(expected, actual) + expected, actual = formatUnequalValues(expected, actual) + return Fail(t, fmt.Sprintf("Not equal: \n"+ + "expected: %s\n"+ + "actual : %s%s", expected, actual, diff), msgAndArgs...) + } + + return true + +} + +// Exactly asserts that two objects are equal in value and type. +// +// assert.Exactly(t, int32(123), int64(123)) +func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + aType := reflect.TypeOf(expected) + bType := reflect.TypeOf(actual) + + if aType != bType { + return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) + } + + return Equal(t, expected, actual, msgAndArgs...) + +} + +// NotNil asserts that the specified object is not nil. +// +// assert.NotNil(t, err) +func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if !isNil(object) { + return true + } + return Fail(t, "Expected value not to be nil.", msgAndArgs...) +} + +// isNil checks if a specified object is nil or not, without Failing. +func isNil(object interface{}) bool { + if object == nil { + return true + } + + value := reflect.ValueOf(object) + kind := value.Kind() + if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { + return true + } + + return false +} + +// Nil asserts that the specified object is nil. +// +// assert.Nil(t, err) +func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if isNil(object) { + return true + } + return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) +} + +// isEmpty gets whether the specified object is considered empty or not. +func isEmpty(object interface{}) bool { + + // get nil case out of the way + if object == nil { + return true + } + + objValue := reflect.ValueOf(object) + + switch objValue.Kind() { + // collection types are empty when they have no element + case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: + return objValue.Len() == 0 + // pointers are empty if nil or if the value they point to is empty + case reflect.Ptr: + if objValue.IsNil() { + return true + } + deref := objValue.Elem().Interface() + return isEmpty(deref) + // for all other types, compare against the zero value + default: + zero := reflect.Zero(objValue.Type()) + return reflect.DeepEqual(object, zero.Interface()) + } +} + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Empty(t, obj) +func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + pass := isEmpty(object) + if !pass { + Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) + } + + return pass + +} + +// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if assert.NotEmpty(t, obj) { +// assert.Equal(t, "two", obj[1]) +// } +func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + pass := !isEmpty(object) + if !pass { + Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) + } + + return pass + +} + +// getLen try to get length of object. +// return (false, 0) if impossible. +func getLen(x interface{}) (ok bool, length int) { + v := reflect.ValueOf(x) + defer func() { + if e := recover(); e != nil { + ok = false + } + }() + return true, v.Len() +} + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// assert.Len(t, mySlice, 3) +func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + ok, l := getLen(object) + if !ok { + return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) + } + + if l != length { + return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) + } + return true +} + +// True asserts that the specified value is true. +// +// assert.True(t, myBool) +func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if h, ok := t.(interface { + Helper() + }); ok { + h.Helper() + } + + if value != true { + return Fail(t, "Should be true", msgAndArgs...) + } + + return true + +} + +// False asserts that the specified value is false. +// +// assert.False(t, myBool) +func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + if value != false { + return Fail(t, "Should be false", msgAndArgs...) + } + + return true + +} + +// NotEqual asserts that the specified values are NOT equal. +// +// assert.NotEqual(t, obj1, obj2) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if err := validateEqualArgs(expected, actual); err != nil { + return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)", + expected, actual, err), msgAndArgs...) + } + + if ObjectsAreEqual(expected, actual) { + return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) + } + + return true + +} + +// containsElement try loop over the list check if the list includes the element. +// return (false, false) if impossible. +// return (true, false) if element was not found. +// return (true, true) if element was found. +func includeElement(list interface{}, element interface{}) (ok, found bool) { + + listValue := reflect.ValueOf(list) + elementValue := reflect.ValueOf(element) + defer func() { + if e := recover(); e != nil { + ok = false + found = false + } + }() + + if reflect.TypeOf(list).Kind() == reflect.String { + return true, strings.Contains(listValue.String(), elementValue.String()) + } + + if reflect.TypeOf(list).Kind() == reflect.Map { + mapKeys := listValue.MapKeys() + for i := 0; i < len(mapKeys); i++ { + if ObjectsAreEqual(mapKeys[i].Interface(), element) { + return true, true + } + } + return true, false + } + + for i := 0; i < listValue.Len(); i++ { + if ObjectsAreEqual(listValue.Index(i).Interface(), element) { + return true, true + } + } + return true, false + +} + +// Contains asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// assert.Contains(t, "Hello World", "World") +// assert.Contains(t, ["Hello", "World"], "World") +// assert.Contains(t, {"Hello": "World"}, "Hello") +func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + ok, found := includeElement(s, contains) + if !ok { + return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) + } + if !found { + return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) + } + + return true + +} + +// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// assert.NotContains(t, "Hello World", "Earth") +// assert.NotContains(t, ["Hello", "World"], "Earth") +// assert.NotContains(t, {"Hello": "World"}, "Earth") +func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + ok, found := includeElement(s, contains) + if !ok { + return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) + } + if found { + return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) + } + + return true + +} + +// Subset asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if subset == nil { + return true // we consider nil to be equal to the nil set + } + + subsetValue := reflect.ValueOf(subset) + defer func() { + if e := recover(); e != nil { + ok = false + } + }() + + listKind := reflect.TypeOf(list).Kind() + subsetKind := reflect.TypeOf(subset).Kind() + + if listKind != reflect.Array && listKind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) + } + + if subsetKind != reflect.Array && subsetKind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) + } + + for i := 0; i < subsetValue.Len(); i++ { + element := subsetValue.Index(i).Interface() + ok, found := includeElement(list, element) + if !ok { + return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) + } + if !found { + return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...) + } + } + + return true +} + +// NotSubset asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if subset == nil { + return Fail(t, fmt.Sprintf("nil is the empty set which is a subset of every set"), msgAndArgs...) + } + + subsetValue := reflect.ValueOf(subset) + defer func() { + if e := recover(); e != nil { + ok = false + } + }() + + listKind := reflect.TypeOf(list).Kind() + subsetKind := reflect.TypeOf(subset).Kind() + + if listKind != reflect.Array && listKind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) + } + + if subsetKind != reflect.Array && subsetKind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) + } + + for i := 0; i < subsetValue.Len(); i++ { + element := subsetValue.Index(i).Interface() + ok, found := includeElement(list, element) + if !ok { + return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) + } + if !found { + return true + } + } + + return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) +} + +// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) +func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if isEmpty(listA) && isEmpty(listB) { + return true + } + + aKind := reflect.TypeOf(listA).Kind() + bKind := reflect.TypeOf(listB).Kind() + + if aKind != reflect.Array && aKind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listA, aKind), msgAndArgs...) + } + + if bKind != reflect.Array && bKind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listB, bKind), msgAndArgs...) + } + + aValue := reflect.ValueOf(listA) + bValue := reflect.ValueOf(listB) + + aLen := aValue.Len() + bLen := bValue.Len() + + if aLen != bLen { + return Fail(t, fmt.Sprintf("lengths don't match: %d != %d", aLen, bLen), msgAndArgs...) + } + + // Mark indexes in bValue that we already used + visited := make([]bool, bLen) + for i := 0; i < aLen; i++ { + element := aValue.Index(i).Interface() + found := false + for j := 0; j < bLen; j++ { + if visited[j] { + continue + } + if ObjectsAreEqual(bValue.Index(j).Interface(), element) { + visited[j] = true + found = true + break + } + } + if !found { + return Fail(t, fmt.Sprintf("element %s appears more times in %s than in %s", element, aValue, bValue), msgAndArgs...) + } + } + + return true +} + +// Condition uses a Comparison to assert a complex condition. +func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + result := comp() + if !result { + Fail(t, "Condition failed!", msgAndArgs...) + } + return result +} + +// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics +// methods, and represents a simple func that takes no arguments, and returns nothing. +type PanicTestFunc func() + +// didPanic returns true if the function passed to it panics. Otherwise, it returns false. +func didPanic(f PanicTestFunc) (bool, interface{}) { + + didPanic := false + var message interface{} + func() { + + defer func() { + if message = recover(); message != nil { + didPanic = true + } + }() + + // call the target function + f() + + }() + + return didPanic, message + +} + +// Panics asserts that the code inside the specified PanicTestFunc panics. +// +// assert.Panics(t, func(){ GoCrazy() }) +func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { + return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) + } + + return true +} + +// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) +func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + funcDidPanic, panicValue := didPanic(f) + if !funcDidPanic { + return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) + } + if panicValue != expected { + return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v", f, expected, panicValue), msgAndArgs...) + } + + return true +} + +// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// assert.NotPanics(t, func(){ RemainCalm() }) +func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + if funcDidPanic, panicValue := didPanic(f); funcDidPanic { + return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v", f, panicValue), msgAndArgs...) + } + + return true +} + +// WithinDuration asserts that the two times are within duration delta of each other. +// +// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) +func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + dt := expected.Sub(actual) + if dt < -delta || dt > delta { + return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) + } + + return true +} + +func toFloat(x interface{}) (float64, bool) { + var xf float64 + xok := true + + switch xn := x.(type) { + case uint8: + xf = float64(xn) + case uint16: + xf = float64(xn) + case uint32: + xf = float64(xn) + case uint64: + xf = float64(xn) + case int: + xf = float64(xn) + case int8: + xf = float64(xn) + case int16: + xf = float64(xn) + case int32: + xf = float64(xn) + case int64: + xf = float64(xn) + case float32: + xf = float64(xn) + case float64: + xf = float64(xn) + case time.Duration: + xf = float64(xn) + default: + xok = false + } + + return xf, xok +} + +// InDelta asserts that the two numerals are within delta of each other. +// +// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) +func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + af, aok := toFloat(expected) + bf, bok := toFloat(actual) + + if !aok || !bok { + return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) + } + + if math.IsNaN(af) { + return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...) + } + + if math.IsNaN(bf) { + return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) + } + + dt := af - bf + if dt < -delta || dt > delta { + return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) + } + + return true +} + +// InDeltaSlice is the same as InDelta, except it compares two slices. +func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if expected == nil || actual == nil || + reflect.TypeOf(actual).Kind() != reflect.Slice || + reflect.TypeOf(expected).Kind() != reflect.Slice { + return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) + } + + actualSlice := reflect.ValueOf(actual) + expectedSlice := reflect.ValueOf(expected) + + for i := 0; i < actualSlice.Len(); i++ { + result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...) + if !result { + return result + } + } + + return true +} + +// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if expected == nil || actual == nil || + reflect.TypeOf(actual).Kind() != reflect.Map || + reflect.TypeOf(expected).Kind() != reflect.Map { + return Fail(t, "Arguments must be maps", msgAndArgs...) + } + + expectedMap := reflect.ValueOf(expected) + actualMap := reflect.ValueOf(actual) + + if expectedMap.Len() != actualMap.Len() { + return Fail(t, "Arguments must have the same number of keys", msgAndArgs...) + } + + for _, k := range expectedMap.MapKeys() { + ev := expectedMap.MapIndex(k) + av := actualMap.MapIndex(k) + + if !ev.IsValid() { + return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...) + } + + if !av.IsValid() { + return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...) + } + + if !InDelta( + t, + ev.Interface(), + av.Interface(), + delta, + msgAndArgs..., + ) { + return false + } + } + + return true +} + +func calcRelativeError(expected, actual interface{}) (float64, error) { + af, aok := toFloat(expected) + if !aok { + return 0, fmt.Errorf("expected value %q cannot be converted to float", expected) + } + if af == 0 { + return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") + } + bf, bok := toFloat(actual) + if !bok { + return 0, fmt.Errorf("actual value %q cannot be converted to float", actual) + } + + return math.Abs(af-bf) / math.Abs(af), nil +} + +// InEpsilon asserts that expected and actual have a relative error less than epsilon +func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + actualEpsilon, err := calcRelativeError(expected, actual) + if err != nil { + return Fail(t, err.Error(), msgAndArgs...) + } + if actualEpsilon > epsilon { + return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ + " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...) + } + + return true +} + +// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. +func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if expected == nil || actual == nil || + reflect.TypeOf(actual).Kind() != reflect.Slice || + reflect.TypeOf(expected).Kind() != reflect.Slice { + return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) + } + + actualSlice := reflect.ValueOf(actual) + expectedSlice := reflect.ValueOf(expected) + + for i := 0; i < actualSlice.Len(); i++ { + result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) + if !result { + return result + } + } + + return true +} + +/* + Errors +*/ + +// NoError asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if assert.NoError(t, err) { +// assert.Equal(t, expectedObj, actualObj) +// } +func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if err != nil { + return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...) + } + + return true +} + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Error(t, err) { +// assert.Equal(t, expectedError, err) +// } +func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + if err == nil { + return Fail(t, "An error is expected but got nil.", msgAndArgs...) + } + + return true +} + +// EqualError asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// assert.EqualError(t, err, expectedErrorString) +func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if !Error(t, theError, msgAndArgs...) { + return false + } + expected := errString + actual := theError.Error() + // don't need to use deep equals here, we know they are both strings + if expected != actual { + return Fail(t, fmt.Sprintf("Error message not equal:\n"+ + "expected: %q\n"+ + "actual : %q", expected, actual), msgAndArgs...) + } + return true +} + +// matchRegexp return true if a specified regexp matches a string. +func matchRegexp(rx interface{}, str interface{}) bool { + + var r *regexp.Regexp + if rr, ok := rx.(*regexp.Regexp); ok { + r = rr + } else { + r = regexp.MustCompile(fmt.Sprint(rx)) + } + + return (r.FindStringIndex(fmt.Sprint(str)) != nil) + +} + +// Regexp asserts that a specified regexp matches a string. +// +// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") +// assert.Regexp(t, "start...$", "it's not starting") +func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + match := matchRegexp(rx, str) + + if !match { + Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) + } + + return match +} + +// NotRegexp asserts that a specified regexp does not match a string. +// +// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") +// assert.NotRegexp(t, "^start", "it's not starting") +func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + match := matchRegexp(rx, str) + + if match { + Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) + } + + return !match + +} + +// Zero asserts that i is the zero value for its type. +func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { + return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) + } + return true +} + +// NotZero asserts that i is not the zero value for its type. +func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { + return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) + } + return true +} + +// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. +func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + info, err := os.Lstat(path) + if err != nil { + if os.IsNotExist(err) { + return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) + } + return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) + } + if info.IsDir() { + return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...) + } + return true +} + +// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. +func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + info, err := os.Lstat(path) + if err != nil { + if os.IsNotExist(err) { + return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) + } + return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) + } + if !info.IsDir() { + return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...) + } + return true +} + +// JSONEq asserts that two JSON strings are equivalent. +// +// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + var expectedJSONAsInterface, actualJSONAsInterface interface{} + + if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { + return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) + } + + if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { + return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) + } + + return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) +} + +func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { + t := reflect.TypeOf(v) + k := t.Kind() + + if k == reflect.Ptr { + t = t.Elem() + k = t.Kind() + } + return t, k +} + +// diff returns a diff of both values as long as both are of the same type and +// are a struct, map, slice or array. Otherwise it returns an empty string. +func diff(expected interface{}, actual interface{}) string { + if expected == nil || actual == nil { + return "" + } + + et, ek := typeAndKind(expected) + at, _ := typeAndKind(actual) + + if et != at { + return "" + } + + if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String { + return "" + } + + var e, a string + if ek != reflect.String { + e = spewConfig.Sdump(expected) + a = spewConfig.Sdump(actual) + } else { + e = expected.(string) + a = actual.(string) + } + + diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ + A: difflib.SplitLines(e), + B: difflib.SplitLines(a), + FromFile: "Expected", + FromDate: "", + ToFile: "Actual", + ToDate: "", + Context: 1, + }) + + return "\n\nDiff:\n" + diff +} + +// validateEqualArgs checks whether provided arguments can be safely used in the +// Equal/NotEqual functions. +func validateEqualArgs(expected, actual interface{}) error { + if isFunction(expected) || isFunction(actual) { + return errors.New("cannot take func type as argument") + } + return nil +} + +func isFunction(arg interface{}) bool { + if arg == nil { + return false + } + return reflect.TypeOf(arg).Kind() == reflect.Func +} + +var spewConfig = spew.ConfigState{ + Indent: " ", + DisablePointerAddresses: true, + DisableCapacities: true, + SortKeys: true, +} + +type tHelper interface { + Helper() +} diff --git a/vendor/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go new file mode 100644 index 00000000..c9dccc4d --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/doc.go @@ -0,0 +1,45 @@ +// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. +// +// Example Usage +// +// The following is a complete example using assert in a standard test function: +// import ( +// "testing" +// "github.com/stretchr/testify/assert" +// ) +// +// func TestSomething(t *testing.T) { +// +// var a string = "Hello" +// var b string = "Hello" +// +// assert.Equal(t, a, b, "The two words should be the same.") +// +// } +// +// if you assert many times, use the format below: +// +// import ( +// "testing" +// "github.com/stretchr/testify/assert" +// ) +// +// func TestSomething(t *testing.T) { +// assert := assert.New(t) +// +// var a string = "Hello" +// var b string = "Hello" +// +// assert.Equal(a, b, "The two words should be the same.") +// } +// +// Assertions +// +// Assertions allow you to easily write test code, and are global funcs in the `assert` package. +// All assertion functions take, as the first argument, the `*testing.T` object provided by the +// testing framework. This allows the assertion funcs to write the failings and other details to +// the correct place. +// +// Every assertion function also takes an optional string message as the final argument, +// allowing custom error messages to be appended to the message the assertion method outputs. +package assert diff --git a/vendor/github.com/stretchr/testify/assert/errors.go b/vendor/github.com/stretchr/testify/assert/errors.go new file mode 100644 index 00000000..ac9dc9d1 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/errors.go @@ -0,0 +1,10 @@ +package assert + +import ( + "errors" +) + +// AnError is an error instance useful for testing. If the code does not care +// about error specifics, and only needs to return the error for example, this +// error should be used to make the test code more readable. +var AnError = errors.New("assert.AnError general error for testing") diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions.go b/vendor/github.com/stretchr/testify/assert/forward_assertions.go new file mode 100644 index 00000000..9ad56851 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/forward_assertions.go @@ -0,0 +1,16 @@ +package assert + +// Assertions provides assertion methods around the +// TestingT interface. +type Assertions struct { + t TestingT +} + +// New makes a new Assertions object for the specified TestingT. +func New(t TestingT) *Assertions { + return &Assertions{ + t: t, + } +} + +//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl -include-format-funcs diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go new file mode 100644 index 00000000..df46fa77 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/http_assertions.go @@ -0,0 +1,143 @@ +package assert + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" +) + +// httpCode is a helper that returns HTTP code of the response. It returns -1 and +// an error if building a new request fails. +func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) { + w := httptest.NewRecorder() + req, err := http.NewRequest(method, url, nil) + if err != nil { + return -1, err + } + req.URL.RawQuery = values.Encode() + handler(w, req) + return w.Code, nil +} + +// HTTPSuccess asserts that a specified handler returns a success status code. +// +// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + code, err := httpCode(handler, method, url, values) + if err != nil { + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + return false + } + + isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent + if !isSuccessCode { + Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code)) + } + + return isSuccessCode +} + +// HTTPRedirect asserts that a specified handler returns a redirect status code. +// +// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + code, err := httpCode(handler, method, url, values) + if err != nil { + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + return false + } + + isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect + if !isRedirectCode { + Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code)) + } + + return isRedirectCode +} + +// HTTPError asserts that a specified handler returns an error status code. +// +// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + code, err := httpCode(handler, method, url, values) + if err != nil { + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + return false + } + + isErrorCode := code >= http.StatusBadRequest + if !isErrorCode { + Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code)) + } + + return isErrorCode +} + +// HTTPBody is a helper that returns HTTP body of the response. It returns +// empty string if building a new request fails. +func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { + w := httptest.NewRecorder() + req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) + if err != nil { + return "" + } + handler(w, req) + return w.Body.String() +} + +// HTTPBodyContains asserts that a specified handler returns a +// body that contains a string. +// +// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + body := HTTPBody(handler, method, url, values) + + contains := strings.Contains(body, fmt.Sprint(str)) + if !contains { + Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) + } + + return contains +} + +// HTTPBodyNotContains asserts that a specified handler returns a +// body that does not contain a string. +// +// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + body := HTTPBody(handler, method, url, values) + + contains := strings.Contains(body, fmt.Sprint(str)) + if contains { + Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) + } + + return !contains +}