diff --git a/.github/license-header.txt b/.github/license-header.txt index 2f3e42d87..671c63b9f 100644 --- a/.github/license-header.txt +++ b/.github/license-header.txt @@ -3,6 +3,3 @@ // The OpenSearch Contributors require contributions made to // this file be licensed under the Apache-2.0 license or a // compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. diff --git a/.github/workflows/govulncheck.yml b/.github/workflows/govulncheck.yml deleted file mode 100644 index def4cb37c..000000000 --- a/.github/workflows/govulncheck.yml +++ /dev/null @@ -1,14 +0,0 @@ -name: Run govulncheck - -on: [push, pull_request] - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - name: Checkout code - uses: actions/checkout@v3 - - - name: Run govulncheck - uses: golang/govulncheck-action@v1 \ No newline at end of file diff --git a/.github/workflows/test-integration-unreleased.yml b/.github/workflows/test-integration-unreleased.yml index 3f272d03b..2eb3f8b5e 100644 --- a/.github/workflows/test-integration-unreleased.yml +++ b/.github/workflows/test-integration-unreleased.yml @@ -66,6 +66,8 @@ jobs: - name: Integration test working-directory: go-client run: make test-integ race=true + env: + OPENSEARCH_GO_SKIP_JSON_COMPARE: true - name: Save server logs if: failure() diff --git a/.golangci.yml b/.golangci.yml index 2c9064852..f61ac37fc 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,7 +1,6 @@ run: timeout: 10m modules-download-mode: readonly - issues-exit-code: 0 linters-settings: errcheck: @@ -37,11 +36,21 @@ linters-settings: check-exported: true misspell: locale: US - ignore-words: expect + ignore-words: + - expect + - cancelled prealloc: simple: true range-loops: true for-loops: false + revive: + rules: + - name: exported + severity: error + disabled: false + arguments: + - "checkPrivateReceivers" + - "sayRepetitiveInsteadOfStutters" linters: disable-all: true @@ -76,7 +85,6 @@ linters: - gofumpt - goheader - goimports - - gomnd - gomoddirectives - gomodguard - goprintffuncname @@ -124,8 +132,11 @@ linters: - zerologlint issues: + include: + - EXC0012 + - EXC0014 exclude-rules: - - path: _test\.go + - path: (_test\.go|opensearchapi/internal) linters: - cyclop - dupl @@ -133,7 +144,6 @@ issues: - gochecknoglobals - gochecknoinits - goconst - - gomnd - noctx - linters: - gosec @@ -149,16 +159,17 @@ issues: path: _test\.go - linters: - goconst - text: "string `true` has" path: opensearchapi\/api_ - linters: - errcheck text: "Error return value of `debugLogger.Logf` is not checked" - linters: - errcheck - - gomnd - gochecknoglobals path: opensearchtransport\/logger\.go - linters: - nestif path: opensearchtransport/opensearchtransport.go + - linters: + - dupl + path: (-params\.go|api_indices|api_dangling\.go|api_point_in_time\.go|rethrottle\.go|api_cat-.*\.go) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1653b86b1..46619c3a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - Adds `Err()` function to Response for detailed errors ([#246](https://github.com/opensearch-project/opensearch-go/pull/246)) - Adds golangci-lint as code analysis tool ([#313](https://github.com/opensearch-project/opensearch-go/pull/313)) - Adds govulncheck to check for go vulnerablities ([#405](https://github.com/opensearch-project/opensearch-go/pull/405)) +- Adds opensearchapi with new client and function structure ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- Adds integration tests for all opensearchapi functions ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) ### Changed @@ -27,6 +29,10 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - Updated Developer guide to include docker build instructions ([#385](https://github.com/opensearch-project/opensearch-go/pull/385)) - Test against version 2.9.0,2.10.0, run tests in all branches, change intergration tests to wait for OpenSearch to start ([#392](https://github.com/opensearch-project/opensearch-go/pull/392)) - Makefile: use docker golangci-lint, run integration test on `.` folder, change coverage generation ([#392](https://github.com/opensearch-project/opensearch-go/pull/392)) +- golangci-lint: update rules and fail when issues are found ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- go: update to golang version 1.20 ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- guids: updated to work for the new opensearchapi ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- Test adjusted to new opensearchapi functions and structs ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) ### Deprecated @@ -34,6 +40,9 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ### Removed +- Removes all old opensearchapi functions ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) +- Removes /internal/build code and folders ([#421](https://github.com/opensearch-project/opensearch-go/pull/421)) + ### Fixed - Corrects AWSv4 signature on DataStream Stats with no index name specified ([#338](https://github.com/opensearch-project/opensearch-go/pull/338)) @@ -41,4 +50,4 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ### Security -[Unreleased]: https://github.com/opensearch-project/opensearch-go/compare/v2.3.0...HEAD \ No newline at end of file +[Unreleased]: https://github.com/opensearch-project/opensearch-go/compare/v2.3.0...HEAD diff --git a/DEVELOPER_GUIDE.md b/DEVELOPER_GUIDE.md index 843cfee8f..9add4aad6 100644 --- a/DEVELOPER_GUIDE.md +++ b/DEVELOPER_GUIDE.md @@ -29,13 +29,13 @@ Fork [opensearch-project/opensearch-go](https://github.com/opensearch-project/op ### Install Prerequisites -#### Go 1.15 +#### Go 1.20 -OpenSearch Go Client builds using [Go](https://golang.org/doc/install) 1.15 at a minimum. +OpenSearch Go Client builds using [Go](https://go.dev/doc/install) 1.20 at a minimum. #### Docker -[Docker](https://docs.docker.com/install/) is required for building some OpenSearch artifacts and executing integration tests. +[Docker](https://docs.docker.com/get-docker/) is required for building some OpenSearch artifacts and executing integration tests. #### Windows diff --git a/Makefile b/Makefile index 65483b95f..0ffd990ee 100644 --- a/Makefile +++ b/Makefile @@ -72,12 +72,6 @@ lint: ## Run lint on the package @printf "\033[2m→ Running lint...\033[0m\n" go vet github.com/opensearch-project/opensearch-go/... go list github.com/opensearch-project/opensearch-go/... | 'grep' -v internal | xargs golint -set_exit_status - @{ \ - set -e ; \ - trap "test -d ../../../.git && git checkout --quiet go.mod" INT TERM EXIT; \ - echo "cd internal/build/ && go vet ./..."; \ - cd "internal/build/" && go mod tidy && go mod download && go vet ./...; \ - } package := "prettier" lint.markdown: @@ -218,7 +212,7 @@ cluster.clean: ## Remove unused Docker volumes and networks docker system prune --volumes --force linters: - docker run -t --rm -v $$(pwd):/app -v ~/.cache/golangci-lint/v1.53.3:/root/.cache -w /app golangci/golangci-lint:v1.53.3 golangci-lint run --timeout=5m + docker run -t --rm -v $$(pwd):/app -v ~/.cache/golangci-lint/v1.54.2:/root/.cache -w /app golangci/golangci-lint:v1.54.2 golangci-lint run --timeout=5m workflow: ## Run all github workflow commands here sequentially diff --git a/UPGRADING.md b/UPGRADING.md index d09583b4d..c80a6f014 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -1,52 +1,157 @@ - [Upgrading Opensearch GO Client](#upgrading-opensearch-go-client) - [Upgraading to >= 3.0.0](#upgrading-to->=-3.0.0) - - [opensearchapi](#opensearchapi-snapshot-delete) - - [opensearchapi](#opensearchapi-error-handling) + - [client creation](#client-creation) + - [requests](#requests) + - [responses](#responses) + - [error handing](#error-handling) + - [Upgraading to >= 2.3.0](#upgrading-to->=-2.3.0) + - [snapshot delete](#snapshot-delete) # Upgrading Opensearch GO Client ## Upgrading to >= 3.0.0 -### opensearchapi snapshot delete +Version 3.0.0 is a major refactor of the client. -`SnapshotDeleteRequest` and `SnapshotDelete` changed the argument `Snapshot` type from `string` to `[]string`. +### Client Creation +You now create the client from the opensearchapi and not from the opensearch lib. This was done to make the different APIs independent from each other. Plugin APIs like Security will get there own folder and therefore its own sub-lib. Before 3.0.0: +```go +// default client +client, err := opensearch.NewDefaultClient() + +// with config +client, err := opensearch.NewClient( + opensearch.Config{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + }, + Addresses: []string{"https://localhost:9200"}, + Username: "admin", + Password: "admin", + }, +) +``` + +With 3.0.0: ```go -// If you have a string containing your snapshot -stringSnapshotsToDelete := "snapshot-1,snapshot-2" -reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ - Repository: repo, - Snapshot: stringSnapshotsToDelete, +// default client +client, err := opensearchapi.NewDefaultClient() + +// with config +client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // For testing only. Use certificate for validation. + }, + Addresses: []string{"https://localhost:9200"}, + Username: "admin", // For testing only. Don't store credentials in code. + Password: "admin", + }, + }, +) +``` + +### Requests + +Prior version 3.0.0 there were two options on how to perform requests. You could either use the request struct of the wished function and execute it with the client .Do() function or use the client function and add wanted args with so called With() functions. With the new version you now use functions attached to the client and give a context and the wanted request body as argument. + +Before 3.0.0: + +```go +// using the client function and adding args by using the With() functions +createIndex, err := client.Indices.Create( + "some-index", + client.Indices.Create.WithContext(ctx), + client.Indices.Create.WithBody(strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`)), +) + +// using the request struct +createIndex := opensearchapi.IndicesCreateRequest{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), } +createIndexResponse, err := createIndex.Do(ctx, client) +``` -// If you have a slice of strings containing your snapshot -sliceSnapshotToDelete := []string{"snapshot-1","snapshot-2"} -reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ - Repository: repo, - Snapshot: strings.Join(sliceSnapshotsToDelete, ","), +With 3.0.0: + +```go +createIndexResponse, err := client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), + }, +) +``` + + +### Responses + +With the version 3.0.0 the lib no longer returns the opensearch.Response which is just a wrap up http.Response. Instead it will check the response for errors and try to parse the body into existing structs. Please note that some responses are so complex that we parse them as [json.RawMessage](https://pkg.go.dev/encoding/json#RawMessage) so you can parse them to your expected struct. If you need the opensearch.Response, then you can call .Inspect(). + +Before 3.0.0: + +```go +// Create the request +createIndex := opensearchapi.IndicesCreateRequest{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), } +// Execute the requests +resp, err := createIndex.Do(ctx, client) +if err != nil { + return err +} +// Close the body +defer resp.Body.Close() + +// Check if the status code is >299 +if resp.IsError() { + return fmt.Errorf("Opensearch Returned an error: %#v", resp) +} + +// Create a struct that represents the create index response +createResp := struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Index string `json:"index"` +} + +// Try to parse the response into the created struct +if err := json.NewDecoder(resp.Body).Decode(&createResp); err != nil { + return fmt.Errorf("Undexpected response body: %s, %#v, %s"resp.StatusCode, resp.Body, err) +} +// Print the created index name +fmt.Println(createResp.Index) ``` With 3.0.0: ```go -// If you have a string containing your snapshots -stringSnapshotsToDelete := strings.Split("snapshot-1,snapshot-2", ",") -reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ - Repository: repo, - Snapshot: stringSnapshotsToDelete, +// Create and execute the requests +createResp, err := client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), + }, +) +if err != nil { + return err } +// Print the created index name +fmt.Println(createResp.Index) -// If you have a slice of strings containing your snapshots -sliceSnapshotToDelete := []string{"snapshot-1", "snapshot-2"} -reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ - Repository: repo, - Snapshot: sliceSnapshotsToDelete, +// To get the opensearch.Response/http.Response +rawResp := createResp.Inspect().Response ``` -### opensearchapi error handling +### Error Handling With opensearch-go >= 3.0.0 opensearchapi responses are now checked for errors. Checking for errors twice is no longer needed. @@ -55,16 +160,21 @@ Prior versions only returned an error if the request failed to execute. For exam Before 3.0.0: ```go +// Create the request createIndex := opensearchapi.IndicesCreateRequest{ - Index: IndexName, - Body: mapping, + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), } -ctx := context.Background() -createIndexResp, err := createIndex.Do(ctx, client) +// Execute the requests +resp, err := createIndex.Do(ctx, client) if err != nil { - return err + return err } +// Close the body +defer resp.Body.Close() + +// Check if the status code is >299 if createIndexResp.IsError() { fmt.Errorf("Opensearch returned an error. Status: %d", createIndexResp.StatusCode) } @@ -73,15 +183,15 @@ if createIndexResp.IsError() { With 3.0.0: ```go -createIndex := opensearchapi.IndicesCreateRequest{ - Index: IndexName, - Body: mapping, -} - -ctx := context.Background() -var opensearchError *opensearchapi.Error - -createIndexResponse, err := createIndex.Do(ctx, client) +var opensearchError opensearchapi.Error +// Create and execute the requests +createResp, err := client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: "some-index", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":4}}}`), + }, +) // Load err into opensearchapi.Error to access the fields and tolerate if the index already exists if err != nil { if errors.As(err, &opensearchError) { @@ -93,3 +203,44 @@ if err != nil { } } ``` + +## Upgrading to >= 2.3.0 + +### Snapshot Delete + +`SnapshotDeleteRequest` and `SnapshotDelete` changed the argument `Snapshot` type from `string` to `[]string`. + +Before 2.3.0: + +```go +// If you have a string containing your snapshot +stringSnapshotsToDelete := "snapshot-1,snapshot-2" +reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ + Repository: repo, + Snapshot: stringSnapshotsToDelete, +} + +// If you have a slice of strings containing your snapshot +sliceSnapshotToDelete := []string{"snapshot-1","snapshot-2"} +reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ + Repository: repo, + Snapshot: strings.Join(sliceSnapshotsToDelete, ","), +} +``` + +With 2.3.0: + +```go +// If you have a string containing your snapshots +stringSnapshotsToDelete := strings.Split("snapshot-1,snapshot-2", ",") +reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ + Repository: repo, + Snapshot: stringSnapshotsToDelete, +} + +// If you have a slice of strings containing your snapshots +sliceSnapshotToDelete := []string{"snapshot-1", "snapshot-2"} +reqSnapshots := &opensearchapi.SnapshotDeleteRequest{ + Repository: repo, + Snapshot: sliceSnapshotsToDelete, +``` diff --git a/USER_GUIDE.md b/USER_GUIDE.md index 616a60d50..fb2636814 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -23,9 +23,9 @@ import ( "os" "strings" - opensearch "github.com/opensearch-project/opensearch-go/v2" - opensearchapi "github.com/opensearch-project/opensearch-go/v2/opensearchapi" - opensearchutil "github.com/opensearch-project/opensearch-go/v2/opensearchutil" + "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + "github.com/opensearch-project/opensearch-go/v2/opensearchutil" ) const IndexName = "go-test-index1" @@ -38,22 +38,30 @@ func main() { } func example() error { - // Initialize the client with SSL/TLS enabled. - client, err := opensearch.NewClient(opensearch.Config{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // For testing only. Use certificate for validation. + client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // For testing only. Use certificate for validation. + }, + Addresses: []string{"https://localhost:9200"}, + Username: "admin", // For testing only. Don't store credentials in code. + Password: "admin", + }, }, - Addresses: []string{"https://localhost:9200"}, - Username: "admin", // For testing only. Don't store credentials in code. - Password: "admin", - }) + ) if err != nil { return err } + ctx := context.Background() // Print OpenSearch version information on console. - fmt.Println(client.Info()) + infoResp, err := client.Info(ctx, nil) + if err != nil { + return err + } + fmt.Printf("Cluster INFO:\n Cluster Name: %s\n Cluster UUID: %s\n Version Number: %s\n", infoResp.ClusterName, infoResp.ClusterUUID, infoResp.Version.Number) // Define index mapping. // Note: these particular settings (eg, shards/replicas) @@ -67,13 +75,14 @@ func example() error { }`) // Create an index with non-default settings. - createIndex := opensearchapi.IndicesCreateRequest{ - Index: IndexName, - Body: mapping, - } - ctx := context.Background() - var opensearchError *opensearchapi.Error - createIndexResponse, err := createIndex.Do(ctx, client) + var opensearchError opensearchapi.Error + createIndexResponse, err := client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: IndexName, + Body: mapping, + }, + ) // Load err into opensearchapi.Error to access the fields and tolerate if the index already exists if err != nil { if errors.As(err, &opensearchError) { @@ -84,7 +93,7 @@ func example() error { return err } } - fmt.Println(createIndexResponse) + fmt.Printf("Created Index: %s\n Shards Acknowledged: %t\n", createIndexResponse.Index, createIndexResponse.ShardsAcknowledged) // When using a structure, the conversion process to io.Reader can be omitted using utility functions. document := struct { @@ -98,16 +107,18 @@ func example() error { } docId := "1" - req := opensearchapi.IndexRequest{ - Index: IndexName, - DocumentID: docId, - Body: opensearchutil.NewJSONReader(&document), - } - insertResponse, err := req.Do(ctx, client) + insertResp, err := client.Index( + ctx, + opensearchapi.IndexReq{ + Index: IndexName, + DocumentID: docId, + Body: opensearchutil.NewJSONReader(&document), + } + ) if err != nil { return err } - fmt.Println(insertResponse) + fmt.Printf("Created document in %s\n ID: %s\n", insertResp.Index, insertResp.ID) // Search for the document. content := strings.NewReader(`{ @@ -120,47 +131,60 @@ func example() error { } }`) - search := opensearchapi.SearchRequest{ - Body: content, - } - - searchResponse, err := search.Do(ctx, client) + searchResp, err := client.Search( + ctx, + &opensearchapi.SearchReq{ + Body: content, + } + ) if err != nil { return err } - fmt.Println(searchResponse) - - // Delete the document. - deleteReq := opensearchapi.DeleteRequest{ - Index: IndexName, - DocumentID: docId, + if searchResp.Hits.Total.Value > 0 { + indices := make([]string, 0) + for _, hit := range searchResp.Hits.Hits { + add := true + for _, index := range indices { + if index == hit.Index { + add = false + } + } + if add { + indices = append(indices, hit.Index) + } + } + fmt.Printf("Search indices: %s\n", strings.Join(indices, ",")) } - deleteResponse, err := deleteReq.Do(ctx, client) - if err != nil { - return err - } - fmt.Println("deleting document") - fmt.Println(deleteResponse) + /* + // Delete the document. + deleteReq := opensearchapi.DeleteReq{ + Index: IndexName, + DocumentID: docId, + } + deleteResponse, err := client.Indices.Delete(ctx, deleteReq) + if err != nil { + return err + } + fmt.Println("deleting document") + fmt.Println(deleteResponse) + */ // Delete previously created index. - deleteIndex := opensearchapi.IndicesDeleteRequest{ - Index: []string{IndexName}, - } - deleteIndexResponse, err := deleteIndex.Do(ctx, client) + deleteIndexResp, err := client.Indices.Delete(ctx, opensearchapi.IndicesDeleteReq{Index: []string{IndexName}}) if err != nil { return err } - fmt.Println("deleting index", deleteIndexResponse) + fmt.Println(fmt.Sprintf("Deleted index: %t", deleteIndexResp.Acknowledged)) // Try to delete the index again which failes as it does not exist // Load err into opensearchapi.Error to access the fields and tolerate if the index is missing - _, err = deleteIndex.Do(ctx, client) + _, err = client.Indices.Delete(ctx, deleteIndex) if err != nil { if errors.As(err, &opensearchError) { if opensearchError.Err.Type != "index_not_found_exception" { - return err + return nil } } else { return err @@ -191,20 +215,28 @@ package main import ( "context" - "io" - "log" + "fmt" + "os" "github.com/aws/aws-sdk-go/aws/session" + requestsigner "github.com/opensearch-project/opensearch-go/v2/signer/aws" + "github.com/opensearch-project/opensearch-go/v2" "github.com/opensearch-project/opensearch-go/v2/opensearchapi" - requestsigner "github.com/opensearch-project/opensearch-go/v2/signer/aws" ) -const endpoint = "" // e.g. https://opensearch-domain.region.com +const IndexName = "go-test-index1" func main() { - ctx := context.Background() + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} + +const endpoint = "" // e.g. https://opensearch-domain.region.com +func example() error { // Create an AWS request Signer and load AWS configuration using default config folder or env vars. // See https://docs.aws.amazon.com/opensearch-service/latest/developerguide/request-signing.html#request-signing-go signer, err := requestsigner.NewSignerWithService( @@ -212,27 +244,31 @@ func main() { requestsigner.OpenSearchService, // Use requestsigner.OpenSearchServerless for Amazon OpenSearch Serverless. ) if err != nil { - log.Fatalf("failed to create signer: %v", err) // Do not log.fatal in a production ready app. + return err } - // Create an opensearch client and use the request-signer. - client, err := opensearch.NewClient(opensearch.Config{ - Addresses: []string{endpoint}, - Signer: signer, - }) + client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{endpoint}, + Signer: signer, + }, + }, + ) if err != nil { - log.Fatalf("failed to create new opensearch client: %v", err) + return err } - ping := opensearchapi.PingRequest{} + ctx := context.Background() + + ping, err := client.Ping(ctx, nil) + if err != nil { + return err + } - resp, err := ping.Do(ctx, client) - if err != nil { - log.Fatalf("failed to ping: %v", err) - } - defer resp.Body.Close() + fmt.Println(ping) - log.Println("PING OK") + return nil } ``` @@ -245,19 +281,27 @@ package main import ( "context" - "log" + "fmt" + "os" "strings" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" - opensearch "github.com/opensearch-project/opensearch-go/v2" - opensearchapi "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + + "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" requestsigner "github.com/opensearch-project/opensearch-go/v2/signer/awsv2" ) const endpoint = "" // e.g. https://opensearch-domain.region.com or Amazon OpenSearch Serverless endpoint func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} +func example() error { ctx := context.Background() awsCfg, err := config.LoadDefaultConfig(ctx, @@ -267,22 +311,26 @@ func main() { ), ) if err != nil { - log.Fatalf("failed to load aws configuraiton: %v", err) // Do not log.fatal in a production ready app. + return err } // Create an AWS request Signer and load AWS configuration using default config folder or env vars. signer, err := requestsigner.NewSignerWithService(awsCfg, "es") // Use "aoss" for Amazon OpenSearch Serverless if err != nil { - log.Fatalf("failed to create signer: %v", err) + return err } // Create an opensearch client and use the request-signer. - client, err := opensearch.NewClient(opensearch.Config{ - Addresses: []string{endpoint}, - Signer: signer, - }) + client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{endpoint}, + Signer: signer, + }, + }, + ) if err != nil { - log.Fatalf("failed to create new opensearch client: %v", err) + return err } indexName := "go-test-index" @@ -297,26 +345,26 @@ func main() { }`) // Create an index with non-default settings. - createIndex := opensearchapi.IndicesCreateRequest{ - Index: indexName, - Body: mapping, - } - createIndexResponse, err := createIndex.Do(ctx, client) + createResp, err := client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: indexName, + Body: mapping, + }, + ) if err != nil { - log.Fatalf("failed to create index: %v", err) + return err } - log.Printf("created index: %#v", createIndexResponse) - // Delete previously created index. - deleteIndex := opensearchapi.IndicesDeleteRequest{ - Index: []string{indexName}, - } + fmt.Println("created index: %s", createResp.Index) - deleteIndexResponse, err := deleteIndex.Do(ctx, client) + delResp, err := client.Indices.Delete(ctx, opensearchapi.IndicesDeleteReq{Indices: []string{indexName}}) if err != nil { - log.Fatalf("failed to delete index: %v", err) + return err } - log.Printf("deleted index: %#v", deleteIndexResponse) + + fmt.Println("deleted index: %#v", delResp.Acknowledged) + return nil } func getCredentialProvider(accessKey, secretAccessKey, token string) aws.CredentialsProviderFunc { @@ -329,7 +377,6 @@ func getCredentialProvider(accessKey, secretAccessKey, token string) aws.Credent return *c, nil } } - ``` ## Guides by Topic diff --git a/doc.go b/doc.go index c6c44dcf7..b2bfd6398 100644 --- a/doc.go +++ b/doc.go @@ -29,7 +29,7 @@ Package opensearch provides a Go client for OpenSearch. Create the client with the NewDefaultClient function: - opensearch.NewDefaultClient() + opensearch.NewDefaultClient() The OPENSEARCH_URL/ELASTICSEARCH_URL environment variable is used instead of the default URL, when set. Use a comma to separate multiple URLs. @@ -37,35 +37,35 @@ It is an error to set both environment variable. To configure the client, pass a Config object to the NewClient function: - cfg := opensearch.Config{ - Addresses: []string{ - "http://localhost:9200", - "http://localhost:9201", - }, - Username: "foo", - Password: "bar", - Transport: &http.Transport{ - MaxIdleConnsPerHost: 10, - ResponseHeaderTimeout: time.Second, - DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, - TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS11, - }, - }, - } + cfg := opensearch.Config{ + Addresses: []string{ + "http://localhost:9200", + "http://localhost:9201", + }, + Username: "foo", + Password: "bar", + Transport: &http.Transport{ + MaxIdleConnsPerHost: 10, + ResponseHeaderTimeout: time.Second, + DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS11, + }, + }, + } - opensearch.NewClient(cfg) + opensearch.NewClient(cfg) See the opensearch_integration_test.go file for more information. Call the OpenSearch APIs by invoking the corresponding methods on the client: - res, err := client.Info() - if err != nil { - log.Fatalf("Error getting response: %s", err) - } + res, err := client.Info() + if err != nil { + log.Fatalf("Error getting response: %s", err) + } - log.Println(res) + log.Println(res) See the github.com/opensearch-project/opensearch-go/opensearchapi package for more information about using the API. diff --git a/go.mod b/go.mod index d4beda0c2..5f04bd0ef 100644 --- a/go.mod +++ b/go.mod @@ -1,11 +1,29 @@ module github.com/opensearch-project/opensearch-go/v2 -go 1.15 +go 1.20 require ( github.com/aws/aws-sdk-go v1.47.4 github.com/aws/aws-sdk-go-v2 v1.22.1 github.com/aws/aws-sdk-go-v2/config v1.22.1 - github.com/kinbiko/jsonassert v1.1.1 github.com/stretchr/testify v1.8.4 + github.com/wI2L/jsondiff v0.4.0 + golang.org/x/exp v0.0.0-20231006140011-7918f672742d +) + +require ( + github.com/aws/aws-sdk-go-v2/credentials v1.15.1 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.2 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.1 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.1 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.5.0 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.10.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.17.0 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.19.0 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.25.0 // indirect + github.com/aws/smithy-go v1.16.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/jmespath/go-jmespath v0.4.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 37b7f63f6..69f6a57e9 100644 --- a/go.sum +++ b/go.sum @@ -28,67 +28,22 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= -github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/kinbiko/jsonassert v1.1.1 h1:DB12divY+YB+cVpHULLuKePSi6+ui4M/shHSzJISkSE= -github.com/kinbiko/jsonassert v1.1.1/go.mod h1:NO4lzrogohtIdNUNzx8sdzB55M4R4Q1bsrWVdqQ7C+A= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= -golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= -golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +github.com/wI2L/jsondiff v0.4.0 h1:iP56F9tK83eiLttg3YdmEENtZnwlYd3ezEpNNnfZVyM= +github.com/wI2L/jsondiff v0.4.0/go.mod h1:nR/vyy1efuDeAtMwc3AF6nZf/2LD1ID8GTyyJ+K8YB0= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/guides/advanced_index_actions.md b/guides/advanced_index_actions.md index 153753b81..45a12c6ad 100644 --- a/guides/advanced_index_actions.md +++ b/guides/advanced_index_actions.md @@ -10,82 +10,93 @@ Let's create a client instance, and an index named `movies`: package main import ( - "github.com/opensearch-project/opensearch-go/v2" - "log" + "context" + "fmt" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" ) func main() { - client, err := opensearch.NewDefaultClient() - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", client) -} - -movies := "movies" - -createMovieIndex, err := client.Indices.Create(movies) -if err != nil { -log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", createMovieIndex) + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + ctx := context.Background() + exampleIndex := "movies" + + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: exampleIndex}) + if err != nil { + return err + } + fmt.Printf("Index created: %t\n", createResp.Acknowledged) ``` ## API Actions ### Clear index cache -You can clear the cache of an index or indices by using the `indices.clear_cache` API action. The following example clears the cache of the `movies` index: +You can clear the cache of an index or indices by using the `Indices.ClearCache()` action. The following example clears the cache of the `movies` index: ```go -res, err := client.Indices.ClearCache(client.Indices.ClearCache.WithIndex(movies)) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + clearCachResp, err := client.Indices.ClearCache(ctx, &opensearchapi.IndicesClearCacheReq{Indices: []string{exampleIndex}}) + if err != nil { + return err + } + fmt.Printf("Cach cleared for %s shards\n", clearCacheResp.Shards.Total) ``` -By default, the `indices.clear_cache` API action clears all types of cache. To clear specific types of cache pass the the `query`, `fielddata`, or `request` parameter to the API action: +By default, the `Indices.ClearCache()` action clears all types of cache. To clear specific types of cache pass the the `query`, `fielddata`, or `request` parameter to the action: ```go -res, err := client.Indices.ClearCache( - client.Indices.ClearCache.WithIndex(movies), - client.Indices.ClearCache.WithFielddata(true), - client.Indices.ClearCache.WithRequest(true), - client.Indices.ClearCache.WithQuery(true), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + clearCachResp, err := client.Indices.ClearCache( + ctx, + &opensearchapi.IndicesClearCacheReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.IndicesClearCacheParams{ + Fielddata: opensearchapi.ToPointer(true), + Request: opensearchapi.ToPointer(true), + Query: opensearchapi.ToPointer(true), + }, + }, + ) + if err != nil { + return err + } + fmt.Printf("Cach cleared for %s shards\n", clearCacheResp.Shards.Total) ``` ### Flush index -Sometimes you might want to flush an index or indices to make sure that all data in the transaction log is persisted to the index. To flush an index or indices use the `indices.flush` API action. The following example flushes the `movies` index: +Sometimes you might want to flush an index or indices to make sure that all data in the transaction log is persisted to the index. To flush an index or indices use the `Indices.Flush()` action. The following example flushes the `movies` index: ```go -res, err := client.Indices.Flush( - client.Indices.Flush.WithIndex(movies), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + flushResp, err := client.Indices.Flush(ctx, &opensearchapi.IndicesFlushReq{Indices: []string{exampleIndex}}) + if err != nil { + return err + } + fmt.Printf("Flushed shards: %d\n", flushResp.Shards.Total) ``` ### Refresh index -You can refresh an index or indices to make sure that all changes are available for search. To refresh an index or indices use the `indices.refresh` API action: +You can refresh an index or indices to make sure that all changes are available for search. To refresh an index or indices use the `Indices.Refresh()` action: ```go -res, err := client.Indices.Refresh( - client.Indices.Refresh.WithIndex(movies), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + refreshResp, err := client.Indices.Refresh(ctx, &opensearchapi.IndicesRefreshReq{Indices: []string{exampleIndex}}) + if err != nil { + return err + } + fmt.Printf("Refreshed shards: %d\n", refreshResp.Shards.Total) ``` ### Open/Close index @@ -93,17 +104,17 @@ log.Printf("response: [%+v]", res) You can close an index to prevent read and write operations on the index. A closed index does not have to maintain certain data structures that an opened index require, reducing the memory and disk space required by the index. The following example closes and reopens the `movies` index: ```go -res, err := client.Indices.Close([]string{movies}) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -res, err = client.Indices.Open([]string{movies}) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + closeResp, err := client.Indices.Close(ctx, opensearchapi.IndicesCloseReq{Index: exampleIndex}) + if err != nil { + return err + } + fmt.Printf("Index closed: %t\n", closeResp.Acknowledged) + + openResp, err := client.Indices.Open(ctx, opensearchapi.IndicesOpenReq{Index: exampleIndex}) + if err != nil { + return err + } + fmt.Printf("Index opended: %t\n", openResp.Acknowledged) ``` ### Force merge index @@ -111,13 +122,19 @@ log.Printf("response: [%+v]", res) You can force merge an index or indices to reduce the number of segments in the index. This can be useful if you have a large number of small segments in the index. Merging segments reduces the memory footprint of the index. Do note that this action is resource intensive and it is only recommended for read-only indices. The following example force merges the `movies` index: ```go -res, err := client.Indices.Forcemerge( - client.Indices.Forcemerge.WithIndex(movies), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + mergeResp, err := client.Indices.Forcemerge( + ctx, + &opensearchapi.IndicesForcemergeReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.IndicesForcemergeParams{ + MaxNumSegments: opensearchapi.ToPointer(1), + }, + }, + ) + if err != nil { + return err + } + fmt.Printf("Forcemerged Shards: %d\n", mergeResp.Shards.Total) ``` ### Clone index @@ -125,26 +142,41 @@ log.Printf("response: [%+v]", res) You can clone an index to create a new index with the same mappings, data, and MOST of the settings. The source index must be in read-only state for cloning. The following example blocks write operations from `movies` index, clones the said index to create a new index named `movies_clone`, then re-enables write: ```go -res, err := client.Indices.AddBlock([]string{movies}, "write") -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -res, err = client.Indices.Clone(movies, "movies_clone") -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -res, err = client.Indices.PutSettings( - strings.NewReader(`{"index":{"blocks":{"write":false}}}`), - client.Indices.PutSettings.WithIndex(movies), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + blockResp, err := client.Indices.Block( + ctx, + opensearchapi.IndicesBlockReq{ + Indices: []string{exampleIndex}, + Block: "write", + }, + ) + if err != nil { + return err + } + fmt.Printf("Index write blocked: %t\n", blockResp.Acknowledged) + + cloneResp, err := client.Indices.Clone( + ctx, + opensearchapi.IndicesCloneReq{ + Index: exampleIndex, + Target: "movies_cloned", + }, + ) + if err != nil { + return err + } + fmt.Printf("Cloned: %t\n", cloneResp.Acknowledged) + + settingResp, err := client.Indices.Settings.Put( + ctx, + opensearchapi.SettingsPutReq{ + Indices: []string{exampleIndex}, + Body: strings.NewReader(`{"index":{"blocks":{"write":null}}}`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Settings updated: %t\n", settingResp.Acknowledged) ``` ### Split index @@ -152,44 +184,52 @@ log.Printf("response: [%+v]", res) You can split an index into another index with more primary shards. The source index must be in read-only state for splitting. The following example create the read-only `books` index with 30 routing shards and 5 shards (which is divisible by 30), splits index into `bigger_books` with 10 shards (which is also divisible by 30), then re-enables write: ```go -books := "books" - -res, err := client.Indices.Create(books, - client.Indices.Create.WithBody( - strings.NewReader(`{ - "settings": { - "index": { - "number_of_shards": 5, - "number_of_routing_shards": 30, - "blocks": { - "write": true - } + createResp, err = client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: "books", + Body: strings.NewReader(`{ + "settings": { + "index": { + "number_of_shards": 5, + "number_of_routing_shards": 30, + "blocks": { + "write": true } } - }`), - ), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -res, err = client.Indices.Split( - books, "bigger_books", - client.Indices.Split.WithBody(strings.NewReader(`{"settings":{"index":{"number_of_shards": 10}}}`))) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -res, err = client.Indices.PutSettings( - strings.NewReader(`{"index":{"blocks":{"write":false}}}`), - client.Indices.PutSettings.WithIndex(books), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + } + }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Index created: %t\n", createResp.Acknowledged) + + splitResp, err := client.Indices.Split( + ctx, + opensearchapi.IndicesSplitReq{ + Index: "books", + Target: "books-large", + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards": 10}}}`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Index splited: %t\n", splitResp.Acknowledged) + + settingResp, err = client.Indices.Settings.Put( + ctx, + opensearchapi.SettingsPutReq{ + Indices: []string{"books"}, + Body: strings.NewReader(`{"index":{"blocks":{"write":null}}}`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Settings updated: %t\n", settingResp.Acknowledged) ``` ## Cleanup @@ -197,10 +237,18 @@ log.Printf("response: [%+v]", res) Let's delete all the indices we created in this guide: ```go -// movies and books are assigned to variables in the previous examples -deleteIndexes, err = client.Indices.Delete([]string{movies, books, "bigger_books", "movies_clone"}) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"movies*", "books*"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) + + return nil } -log.Printf("response: [%+v]", deleteIndexes) ``` diff --git a/guides/bulk.md b/guides/bulk.md index dca089ca3..8c3a9d16b 100644 --- a/guides/bulk.md +++ b/guides/bulk.md @@ -10,58 +10,79 @@ First, create a client instance with the following code: package main import ( - "github.com/opensearch-project/opensearch-go/v2" - "log" + "context" + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" ) func main() { - client, err := opensearch.NewDefaultClient() - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", client) + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } } + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + ctx := context.Background() ``` Next, create an index named `movies` and another named `books` with the default settings: ```go -movies := "movies" -books := "books" - -createMovieIndex, err := client.Indices.Create(movies) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", createMovieIndex) - -createBooksIndex, err := client.Indices.Create(books) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", createBooksIndex) + movies := "movies" + books := "books" + + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: movies}) + if err != nil { + return err + } + fmt.Printf("Index created: %t\n", createResp.Acknowledged) + + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: books}) + if err != nil { + return err + } + fmt.Printf("Index created: %t\n", createResp.Acknowledged) ``` ## Bulk API -The `bulk` API action allows you to perform document operations in a single request. The body of the request is an array of objects that contains the bulk operations and the target documents to index, create, update, or delete. +The `bulk` API action allows you to perform document operations in a single request. The body of the request consist of minimum two objects that contains the bulk operations and the target documents to index, create, update, or delete. ### Indexing multiple documents The following code creates two documents in the `movies` index and one document in the `books` index: ```go - res, err := client.Bulk(strings.NewReader(`{ "index": { "_index": "movies", "_id": 1 } } + bulkResp, err := client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader(`{ "index": { "_index": "movies", "_id": 1 } } { "title": "Beauty and the Beast", "year": 1991 } { "index": { "_index": "movies", "_id": 2 } } { "title": "Beauty and the Beast - Live Action", "year": 2017 } { "index": { "_index": "books", "_id": 1 } } { "title": "The Lion King", "year": 1994 } -`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) +`), + }, + ) + if err != nil { + return err + } + respAsJson, err := json.MarshalIndent(bulkResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Bulk Resp:\n%s\n", string(respAsJson)) ``` ### Creating multiple documents @@ -69,7 +90,10 @@ The following code creates two documents in the `movies` index and one document Similarly, instead of calling the `create` method for each document, you can use the `bulk` API to create multiple documents in a single request. The following code creates three documents in the `movies` index and one in the `books` index: ```go - res, err = client.Bulk(strings.NewReader(`{ "create": { "_index": "movies" } } + bulkResp, err = client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader(`{ "create": { "_index": "movies" } } { "title": "Beauty and the Beast 2", "year": 2030 } { "create": { "_index": "movies", "_id": 1 } } { "title": "Beauty and the Beast 3", "year": 2031 } @@ -77,11 +101,17 @@ Similarly, instead of calling the `create` method for each document, you can use { "title": "Beauty and the Beast 4", "year": 2049 } { "create": { "_index": "books" } } { "title": "The Lion King 2", "year": 1998 } -`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) +`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(bulkResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Bulk Resp:\n%s\n", string(respAsJson)) ``` We omit the `_id` for each document and let OpenSearch generate them for us in this example, just like we can with the `create` method. @@ -89,15 +119,24 @@ We omit the `_id` for each document and let OpenSearch generate them for us in t ### Updating multiple documents ```go - res, err = client.Bulk(strings.NewReader(`{ "update": { "_index": "movies", "_id": 1 } } + bulkResp, err = client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader(`{ "update": { "_index": "movies", "_id": 1 } } { "doc": { "year": 1992 } } { "update": { "_index": "movies", "_id": 1 } } { "doc": { "year": 2018 } } -`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) +`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(bulkResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Bulk Resp:\n%s\n", string(respAsJson)) ``` Note that the updated data is specified in the `doc` with a full or partial JSON document, depending on how much of the document you want to update. @@ -107,13 +146,22 @@ Note that the updated data is specified in the `doc` with a full or partial JSON If the document doesn’t exist, OpenSearch doesn’t return an error, but instead returns not_found under result. Delete actions don’t require documents on the next line ```go - res, err = client.Bulk(strings.NewReader(`{ "delete": { "_index": "movies", "_id": 1 } } + bulkResp, err = client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader(`{ "delete": { "_index": "movies", "_id": 1 } } { "delete": { "_index": "movies", "_id": 2 } } - `)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + `), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(bulkResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Bulk Resp:\n%s\n", string(respAsJson)) ``` ### Mix and match operations @@ -121,71 +169,52 @@ If the document doesn’t exist, OpenSearch doesn’t return an error, but inste You can mix and match the different operations in a single request. The following code creates two documents, updates one document, and deletes another document: ```go - res, err = client.Bulk(strings.NewReader(`{ "create": { "_index": "movies", "_id": 3 } } + bulkResp, err = client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader(`{ "create": { "_index": "movies", "_id": 3 } } { "title": "Beauty and the Beast 5", "year": 2050 } { "create": { "_index": "movies", "_id": 4 } } { "title": "Beauty and the Beast 6", "year": 2051 } { "update": { "_index": "movies", "_id": 3 } } { "doc": { "year": 2052 } } { "delete": { "_index": "movies", "_id": 4 } } -`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) +`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(bulkResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Bulk Resp:\n%s\n", string(respAsJson)) ``` ### Handling errors The `bulk` API returns an array of responses for each operation in the request body. Each response contains a `status` field that indicates whether the operation was successful or not. If the operation was successful, the `status` field is set to a `2xx` code. Otherwise, the response contains an error message in the `error` field. -The following code shows how to look for errors in the response: +The following code shows an example on how to look for errors in the response: ```go -type Response struct { - Took int `json:"took"` - Errors bool `json:"errors"` - Items []struct { - Delete struct { - Index string `json:"_index"` - Id string `json:"_id"` - Version int `json:"_version"` - Result string `json:"result"` - Shards struct { - Total int `json:"total"` - Successful int `json:"successful"` - Failed int `json:"failed"` - } `json:"_shards"` - SeqNo int `json:"_seq_no"` - PrimaryTerm int `json:"_primary_term"` - Status int `json:"status"` - } `json:"delete,omitempty"` - } `json:"items"` -} - - res, err = client.Bulk(strings.NewReader(`{ "delete": { "_index": "movies", "_id": 10 } } -`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - - body, err := io.ReadAll(res.Body) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - - var response Response - if err := json.Unmarshal(body, &response); err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - - for _, item := range response.Items { - if item.Delete.Status > 299 { - log.Printf("error occurred: [%s]", item.Delete.Result) - } else { - log.Printf("success: [%s]", item.Delete.Result) - } - } + bulkResp, err = client.Bulk( + ctx, + opensearchapi.BulkReq{ + Body: strings.NewReader("{\"delete\":{\"_index\":\"movies\",\"_id\":1}}\n"), + }, + ) + if err != nil { + return err + } + for _, item := range bulkResp.Items { + for operation, resp := range item { + if resp.Status > 299 { + fmt.Printf("Bulk %s Error: %s\n", operation, resp.Result) + } + } + } ``` ## Cleanup @@ -193,12 +222,18 @@ type Response struct { To clean up the resources created in this guide, delete the `movies` and `books` indices: ```go -deleteIndexes, err := client.Indices.Delete( - []string{movies, books}, - client.Indices.Delete.WithIgnoreUnavailable(true), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"movies", "books"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) + + return nil } -log.Printf("response: [%+v]", deleteIndexes) ``` diff --git a/guides/data_streams.md b/guides/data_streams.md index 7a10b723c..a1732c3c3 100644 --- a/guides/data_streams.md +++ b/guides/data_streams.md @@ -1,179 +1,146 @@ -## Data Streams API +# Data Streams API -### Create Data Streams +## Setup -- Create new client +First, create a client instance with the following code: -``` -client, err := opensearch.NewDefaultClient() -if err != nil { - panic(err) -} -``` - -- Create template index - -``` -iPut := opensearchapi.IndicesPutIndexTemplateRequest{ - Name: "demo-data-template", - Pretty: true, - Human: true, - ErrorTrace: true, - Body: strings.NewReader(`{"index_patterns": ["demo-*"], "data_stream": {}, "priority": 100} }`), -} -iPutResponse, err := iPut.Do(context.Background(), client) -``` - -- Prepare request object +```go +package main -``` -es := opensearchapi.IndicesCreateDataStreamRequest{ - Name: "demo-name", - Human: true, - Pretty: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, -} -``` +import ( + "context" + "fmt" + "os" + "strings" -- Execute request + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) -``` -res, err := es.Do(context.TODO(), client) -if err != nil { - // do not panic in production code - panic(err) +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } } -``` -- Try to read response +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + ctx := context.Background() +``` + +Next, create an index template with a data_stream section: + +```go + tempCreateResp, err := client.IndexTemplate.Create( + ctx, + opensearchapi.IndexTemplateCreateReq{ + IndexTemplate: "books", + Body: strings.NewReader(`{ + "index_patterns": ["books-nonfiction"], + "template": { + "settings": { + "index": { + "number_of_shards": 3, + "number_of_replicas": 0 + } + } + }, + "data_stream": {}, + "priority": 50 + }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Index Tempalte created: %t\n", tempCreateResp.Acknowledged) ``` -defer res.Body.Close() -body, err := ioutil.ReadAll(res.Body) -if err != nil { - // do not panic in production code - panic(err) -} -fmt.Println("Response Status Code: ", res.StatusCode) -fmt.Println("Response Headers: ", res.Header) -fmt.Println("Response Body: ", string(body)) -``` +## Create Data Streams -- Successfully created data stream +The `DataStream.Create()` action allows you to create a new Data Stream: -``` -Response Status Code: 200 -Response Headers: map[Content-Length:[28] Content-Type:[application/json; charset=UTF-8]] -Response Body: {"acknowledged" : true} +```go + createResp, err := client.DataStream.Create(ctx, opensearchapi.DataStreamCreateReq{DataStream: "books-nonfiction"}) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) ``` -### Delete Data Streams +## Get Data Streams -- Create new client as previous example -- Prepare request object +The `DataStream.Get()` action allows you to get information about Data Streams. Omitting the Request struct will get all DataStreams: -``` -opensearchapi.IndicesDeleteDataStreamRequest{ - Name: "demo-name", - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, -} +```go + getResp, err := client.DataStream.Get(ctx, nil) + if err != nil { + return err + } + respAsJson, err := json.MarshalIndent(getResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Get DataStream:\n%s\n", string(respAsJson)) ``` -- Execute request as previous example -- Try to read response as previous example -- Successfully deleted data stream +By specifying a Data Stream in the request you'll only see the requested Data Stream: +```go + getResp, err = client.DataStream.Get(ctx, &opensearchapi.DataStreamGetReq{DataStreams: []string{"books-nonfiction"}}) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(getResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Get DataStream:\n%s\n", string(respAsJson)) ``` -Response Status Code: 200 -Response Headers: map[Content-Length:[28] Content-Type:[application/json; charset=UTF-8]] -Response Body: {"acknowledged" : true} -``` - -### Get All Data Streams -- Create new client as previous example -- Prepare request object +## Get Data Stream Stats -``` -r := opensearchapi.IndicesGetDataStreamRequest{ - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, -} -``` +The `DataStream.Stats()` action allows you to get stats about Data Streams: -- Execute request as previous example -- Try to read response as previous example -- Successfully retrieved data streams - -``` -Response Status Code: 200 -Response Headers: map[Content-Length:[28] Content-Type:[application/json; charset=UTF-8]] -Response Body: {"data_streams":[{"name":"demo-name","timestamp_field":{"name":"@timestamp"},"indices":[{"index_name":".ds-demo-2023-03-21-23-33-46-000001","index_uuid":"NnzgqnP0ThS7LOMHJuZ-VQ"}],"generation":1,"status":"YELLOW","template":"demo-data-template"}]} +```go + statsResp, err := client.DataStream.Stats(ctx, nil) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(statsResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Stats DataStream:\n%s\n", string(respAsJson)) ``` -### Get Specific Data Stream +## Delete Data Streams -- Create new client as previous example -- Prepare request object +The `DataStream.Delete()` action allows you to delete a Data Stream: -``` -r := opensearchapi.IndicesGetDataStreamRequest{ - Name: "demo-name", - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, +```go + delResp, err := client.DataStream.Delete(ctx, opensearchapi.DataStreamDeleteReq{DataStream: "books-nonfiction"}) + if err != nil { + return err } + fmt.Printf("DataStream deleted: %t\n", delResp.Acknowledged) ``` -- Execute request as previous example -- Try to read response as previous example -- Successfully retrieved data stream - -``` -Response Status Code: 200 -Response Headers: map[Content-Length:[28] Content-Type:[application/json; charset=UTF-8]] -Response Body: {"data_streams":[{"name":"demo-name","timestamp_field":{"name":"@timestamp"},"indices":[{"index_name":".ds-demo-2023-03-21-23-31-50-000001","index_uuid":"vhsowqdeRFCmr1GgQ7mIsQ"}],"generation":1,"status":"YELLOW","template":"demo-data-template"}]} -``` +## Cleanup -### Get Specific Data Stream Stats +To clean up the resources created in this guide, delete the index template: -- Create new client as as previous example -- Prepare request object +```go + delTempResp, err := client.IndexTemplate.Delete(ctx, opensearchapi.IndexTemplateDeleteReq{IndexTemplate: "books"}) + if err != nil { + return err + } + fmt.Printf("Deleted templates: %t\n", delTempResp.Acknowledged) -``` -r := opensearchapi.IndicesGetDataStreamStatsRequest{ - Name: "demo-name", - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, + return nil } ``` - -- Execute request as previous example -- Try to read response as previous example -- Successfully retrieved data stream stats - -``` -Response Status Code: 200 -Response Headers: map[Content-Length:[28] Content-Type:[application/json; charset=UTF-8]] -Response Body: {"_shards":{"total":2,"successful":1,"failed":0},"data_stream_count":1,"backing_indices":1,"total_store_size":"208b","total_store_size_bytes":208,"data_streams":[{"data_stream":"demo-name","backing_indices":1,"store_size":"208b","store_size_bytes":208,"maximum_timestamp":0}]} -``` diff --git a/guides/document_lifecycle.md b/guides/document_lifecycle.md index 6cfa40a61..682279957 100644 --- a/guides/document_lifecycle.md +++ b/guides/document_lifecycle.md @@ -7,42 +7,41 @@ This guide covers OpenSearch Golang Client API actions for Document Lifecycle. Y Assuming you have OpenSearch running locally on port 9200, you can create a client instance with the following code: ```go - package main - - import ( - "github.com/opensearch-project/opensearch-go/v2" - "log" - ) - - func main() { - client, err := opensearch.NewDefaultClient() - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", client) - } +package main + +import ( + "context" + "fmt" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) + +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + ctx := context.Background() ``` Next, create an index named `movies` with the default settings: ```go - movies := "movies" - - // delete the indexes if they exist - deleteIndexes, err := client.Indices.Delete( - []string{movies}, - client.Indices.Delete.WithIgnoreUnavailable(true), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", deleteIndexes) - - createMovieIndex, err := client.Indices.Create(movies) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", createMovieIndex) + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: "movies"}) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) ``` ## Document API Actions @@ -52,42 +51,64 @@ Next, create an index named `movies` with the default settings: To create a new document, use the `create` or `index` API action. The following code creates two new documents with IDs of `1` and `2`: ```go - res, err := client.Create(movies, "1", strings.NewReader(`{"title": "Beauty and the Beast", "year": 1991 }`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) - - res, err = client.Create(movies, "2", strings.NewReader(`{"title": "Beauty and the Beast - Live Action", "year": 2017 }`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + docCreateResp, err := client.Document.Create( + ctx, + opensearchapi.DocumentCreateReq{ + Index: "movies", + DocumentID: "1", + Body: strings.NewReader(`{"title": "Beauty and the Beast", "year": 1991 }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Document: %s\n", docCreateResp.Result) + + docCreateResp, err = client.Document.Create( + ctx, + opensearchapi.DocumentCreateReq{ + Index: "movies", + DocumentID: "2", + Body: strings.NewReader(`{"title": "Beauty and the Beast - Live Action", "year": 2017 }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Document: %s\n", docCreateResp.Result) ``` Note that the `create` action is NOT idempotent. If you try to create a document with an ID that already exists, the request will fail: ```go - res, err = client.Create(movies, "2", strings.NewReader(`{"title": "Just Another Movie" }`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } + _, err = client.Document.Create( + ctx, + opensearchapi.DocumentCreateReq{ + Index: "movies", + DocumentID: "2", + Body: strings.NewReader(`{"title": "Just Another Movie" }`), + }, + ) + if err != nil { + fmt.Println(err) + } ``` The `index` action, on the other hand, is idempotent. If you try to index a document with an existing ID, the request will succeed and overwrite the existing document. Note that no new document will be created in this case. You can think of the `index` action as an upsert: ```go - res, err = client.Index(movies, strings.NewReader(`{"title": "Updated Title" }`), client.Index.WithDocumentID("2")) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) - - res, err = client.Index(movies, strings.NewReader(`{ "title": "The Lion King", "year": 1994}`), client.Index.WithDocumentID("2")) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + indexResp, err := client.Index( + ctx, + opensearchapi.IndexReq{ + Index: "movies", + DocumentID: "2", + Body: strings.NewReader(`{"title": "Updated Title" }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Document: %s\n", indexResp.Result) ``` ### Create a new document with auto-generated ID @@ -95,11 +116,21 @@ The `index` action, on the other hand, is idempotent. If you try to index a docu You can also create a new document with an auto-generated ID by omitting the `id` parameter. The following code creates documents with an auto-generated IDs in the `movies` index: ```go - res, err = client.Index(movies, strings.NewReader(`{ "title": "The Lion King 2", "year": 1978}`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + indexResp, err = client.Index( + ctx, + opensearchapi.IndexReq{ + Index: "movies", + Body: strings.NewReader(`{ "title": "The Lion King 2", "year": 1978}`), + }, + ) + if err != nil { + return err + } + respAsJson, err := json.MarshalIndent(indexResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Index:\n%s\n", respAsJson) ``` In this case, the ID of the created document in the `result` field of the response body: @@ -125,30 +156,53 @@ In this case, the ID of the created document in the `result` field of the respon To get a document, use the `get` API action. The following code gets the document with ID `1` from the `movies` index: ```go - res, err = client.Get(movies, "1") - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) - // OUTPUT: {"_index":"movies","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"title": "Beauty and the Beast", "year": 1991 }} + getResp, err := client.Document.Get(ctx, opensearchapi.DocumentGetReq{Index: "movies", DocumentID: "1"}) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(getResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", respAsJson) ``` You can also use `_source_include` and `_source_exclude` parameters to specify which fields to include or exclude in the response: ```go - res, err = client.Get(movies, "1", client.Get.WithSourceIncludes("title")) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) - // OUTPUT: {"_index":"movies","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"title":"Beauty and the Beast"}} - - res, err = client.Get(movies, "1", client.Get.WithSourceExcludes("title")) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) - // OUTPUT: {"_index":"movies","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"year":1991}} + getResp, err = client.Document.Get( + ctx, + opensearchapi.DocumentGetReq{ + Index: "movies", + DocumentID: "1", + Params: opensearchapi.DocumentGetParams{SourceIncludes: []string{"title"}}, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(getResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", respAsJson) + + getResp, err = client.Document.Get( + ctx, + opensearchapi.DocumentGetReq{ + Index: "movies", + DocumentID: "1", + Params: opensearchapi.DocumentGetParams{SourceExcludes: []string{"title"}}, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(getResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", respAsJson) ``` ### Get multiple documents @@ -156,12 +210,21 @@ You can also use `_source_include` and `_source_exclude` parameters to specify w To get multiple documents, use the `mget` API action: ```go - res, err = client.Mget(strings.NewReader(`{ "docs": [{ "_id": "1" }, { "_id": "2" }] }`), client.Mget.WithIndex(movies)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) - // OUTPUT: {"docs":[{"_index":"movies","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"title": "Beauty and the Beast", "year": 1991 }},{"_index":"movies","_id":"2","_version":3,"_seq_no":3,"_primary_term":1,"found":true,"_source":{ "title": "The Lion King", "year": 1994}}]} + mgetResp, err := client.MGet( + ctx, + opensearchapi.MGetReq{ + Index: "movies", + Body: strings.NewReader(`{ "docs": [{ "_id": "1" }, { "_id": "2" }] }`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(mgetResp, "", " ") + if err != nil { + return err + } + fmt.Printf("MGet Document:\n%s\n", respAsJson) ``` ### Check if a document exists @@ -169,11 +232,11 @@ To get multiple documents, use the `mget` API action: To check if a document exists, use the `exists` API action. The following code checks if the document with ID `1` exists in the `movies` index: ```go - res, err = client.Exists(movies, "1") - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + existsResp, err := client.Document.Exists(ctx, opensearchapi.DocumentExistsReq{Index: "movies", DocumentID: "1"}) + if err != nil { + return err + } + fmt.Println(existsResp.Status()) ``` ### Update a document @@ -181,21 +244,43 @@ To check if a document exists, use the `exists` API action. The following code c To update a document, use the `update` API action. The following code updates the `year` field of the document with ID `1` in the `movies` index: ```go - res, err = client.Update(movies, "1", strings.NewReader(`{ "doc": { "year": 1995 } }`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + updateResp, err := client.Update( + ctx, + opensearchapi.UpdateReq{ + Index: "movies", + DocumentID: "1", + Body: strings.NewReader(`{ "doc": { "year": 1995 } }`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(updateResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Update:\n%s\n", respAsJson) ``` Alternatively, you can use the `script` parameter to update a document using a script. The following code increments the `year` field of the of document with ID `1` by 5 using painless script, the default scripting language in OpenSearch: ```go - res, err = client.Update(movies, "1", strings.NewReader(`{ "script": { "source": "ctx._source.year += 5" } }`)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + updateResp, err = client.Update( + ctx, + opensearchapi.UpdateReq{ + Index: "movies", + DocumentID: "1", + Body: strings.NewReader(`{ "script": { "source": "ctx._source.year += 5" } }`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(updateResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Update:\n%s\n", respAsJson) ``` Note that while both `update` and `index` actions perform updates, they are not the same. The `update` action is a partial update, while the `index` action is a full update. The `update` action only updates the fields that are specified in the request body, while the `index` action overwrites the entire document with the new document. @@ -205,25 +290,27 @@ Note that while both `update` and `index` actions perform updates, they are not To update documents that match a query, use the `update_by_query` API action. The following code decreases the `year` field of all documents with `year` greater than 2023: ```go - res, err = client.Indices.Refresh( - client.Indices.Refresh.WithIndex(movies), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) - - res, err = client.UpdateByQuery( - []string{movies}, - client.UpdateByQuery.WithQuery("year:<1990"), - client.UpdateByQuery.WithBody( - strings.NewReader(`{"script": { "source": "ctx._source.year -= 1" } }`), - ), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + _, err = client.Indices.Refresh(ctx, &opensearchapi.IndicesRefreshReq{Indices: []string{"movies"}}) + if err != nil { + return err + } + + upByQueryResp, err := client.UpdateByQuery( + ctx, + opensearchapi.UpdateByQueryReq{ + Indices: []string{"movies"}, + Params: opensearchapi.UpdateByQueryParams{Query: "year:<1990"}, + Body: strings.NewReader(`{"script": { "source": "ctx._source.year -= 1" } }`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(upByQueryResp, "", " ") + if err != nil { + return err + } + fmt.Printf("UpdateByQuery:\n%s\n", respAsJson) ``` Note that the `update_by_query` API action is needed to refresh the index before the query is executed. @@ -233,11 +320,15 @@ Note that the `update_by_query` API action is needed to refresh the index before To delete a document, use the `delete` API action. The following code deletes the document with ID `1`: ```go - res, err = client.Delete(movies, "1") - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + docDelResp, err := client.Document.Delete(ctx, opensearchapi.DocumentDeleteReq{Index: "movies", DocumentID: "1"}) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(docDelResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Del Doc:\n%s\n", respAsJson) ``` ### Delete multiple documents by query @@ -245,23 +336,26 @@ To delete a document, use the `delete` API action. The following code deletes th To delete documents that match a query, use the `delete_by_query` API action. The following code deletes all documents with `year` greater than 2023: ```go - res, err = client.Indices.Refresh( - client.Indices.Refresh.WithIndex(movies), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) - - res, err = client.DeleteByQuery( - []string{movies}, - strings.NewReader(`{ "query": { "match": { "title": "The Lion King" } } }`), - client.DeleteByQuery.WithQuery(`title: "The Lion King"`), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + _, err = client.Indices.Refresh(ctx, &opensearchapi.IndicesRefreshReq{Indices: []string{"movies"}}) + if err != nil { + return err + } + + delByQueryResp, err := client.Document.DeleteByQuery( + ctx, + opensearchapi.DocumentDeleteByQueryReq{ + Indices: []string{"movies"}, + Body: strings.NewReader(`{ "query": { "match": { "title": "The Lion King" } } }`), + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(delByQueryResp, "", " ") + if err != nil { + return err + } + fmt.Printf("DelByQuery Doc:\n%s\n", respAsJson) ``` Note that the `delete_by_query` API action is needed to refresh the index before the query is executed. @@ -271,12 +365,18 @@ Note that the `delete_by_query` API action is needed to refresh the index before To clean up the resources created in this guide, delete the `movies` index: ```go - deleteIndexes, err := client.Indices.Delete( - []string{movies}, - client.Indices.Delete.WithIgnoreUnavailable(true), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", deleteIndexes) + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"movies"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) + + return nil +} ``` diff --git a/guides/index_lifecycle.md b/guides/index_lifecycle.md index b7f06c8b3..b07587d3d 100644 --- a/guides/index_lifecycle.md +++ b/guides/index_lifecycle.md @@ -1,6 +1,6 @@ # Index Lifecycle -This guide covers OpenSearch Golang Client API actions for Index Lifecycle. You'll learn how to create, read, update, and delete indices in your OpenSearch cluster. We will also leverage index templates to create default settings and mappings for indices of certain patterns. +This guide covers OpenSearch Golang Client API actions for Index Lifecycle. You'll learn how to create, get, update settings, update mapping, and delete indices in your OpenSearch cluster. We will also leverage index templates to create default settings and mappings for indices of certain patterns. ## Setup @@ -16,135 +16,173 @@ To start the cluster, run the following command: Let's create a client instance to access this cluster: ```go - package main - - import ( - "github.com/opensearch-project/opensearch-go/v2" - "log" - ) +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) + +func main() { + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } +} - func main() { - client, err := opensearch.NewDefaultClient() - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", client) - } +func example() error { + // Initialize the client with SSL/TLS enabled. + client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // For testing only. Use certificate for validation. + }, + Addresses: []string{"https://localhost:9200"}, + Username: "admin", // For testing only. Don't store credentials in code. + Password: "admin", + }, + }, + ) + if err != nil { + return err + } + ctx := context.Background() ``` ## Index API Actions ### Create a new index -You can quickly create an index with default settings and mappings by using the `indices.create` API action. The following example creates an index named `paintings` with default settings and mappings: +You can quickly create an index with default settings and mappings by using the `client.Indices.Create` action. The following example creates an index named `paintings` with default settings and mappings: ```go - paintingsIndex, err := client.Indices.Create("paintings") - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", paintingsIndex) + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: "paintings"}) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) ``` To specify settings and mappings, you can pass them as the `body` of the request. The following example creates an index named `movies` with custom settings and mappings: ```go - movies := "movies" - - createMovieIndex, err := client.Indices.Create(movies, - client.Indices.Create.WithBody(strings.NewReader(`{ - "settings": { - "index": { - "number_of_shards": 2, - "number_of_replicas": 1 - } - }, - "mappings": { - "properties": { - "title": { - "type": "text" - }, - "year": { - "type": "integer" - } - } - } - }`), - ), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", createMovieIndex) + createResp, err = client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: "movies", + Body: strings.NewReader(`{ + "settings": { + "index": { + "number_of_shards": 2, + "number_of_replicas": 1 + } + }, + "mappings": { + "properties": { + "title": { + "type": "text" + }, + "year": { + "type": "integer" + } + } + } + }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) ``` When you create a new document for an index, OpenSearch will automatically create the index if it doesn't exist: ```go // return status code 404 Not Found - res, err := client.Indices.Exists([]string{"burner"}) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) - - res, err = client.Indices.Create( - "burner", - client.Indices.Create.WithBody(strings.NewReader(`{ "settings": {} }`)), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + existsResp, err := client.Indices.Exists(ctx, opensearchapi.IndicesExistsReq{Indices: []string{"burner"}}) + if err != nil { + return err + } + fmt.Printf("%s\n", existsResp) + + indexResp, err := client.Index(ctx, opensearchapi.IndexReq{Index: "burner", Body: strings.NewReader(`{"foo": "bar"}`)}) + if err != nil { + return err + } + fmt.Printf("Index: %s\n", indexResp.Result) // return status code 200 OK - res, err = client.Indices.Exists([]string{"burner"}) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + existsResp, err = client.Indices.Exists(ctx, opensearchapi.IndicesExistsReq{Indices: []string{"burner"}}) + if err != nil { + return err + } + fmt.Printf("%s\n", existsResp) ``` ### Update an Index -You can update an index's settings and mappings by using the `indices.put_settings` and `indices.put_mapping` API actions. +You can update an index's settings and mappings by using the `client.Indices.Settings.Put()` and `client.Indices.Mapping.Put()` actions. The following example updates the `movies` index's number of replicas to `0`: ```go - res, err := client.Indices.PutSettings( - strings.NewReader(`{ "index": { "number_of_replicas": 0} }`), - client.Indices.PutSettings.WithIndex(movies), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + settingsPutResp, err := client.Indices.Settings.Put( + ctx, + opensearchapi.SettingsPutReq{ + Indices: []string{"burner"}, + Body: strings.NewReader(`{"index":{"number_of_replicas":0}}`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Settings updated: %t\n", settingsPutResp.Acknowledged) ``` The following example updates the `movies` index's mappings to add a new field named `director`: ```go - res, err := client.Indices.PutMapping( - strings.NewReader(`{ "properties": { "director": { "type": "text" } } }`), - client.Indices.PutMapping.WithIndex(movies), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + mappingPutResp, err := client.Indices.Mapping.Put( + ctx, + opensearchapi.MappingPutReq{ + Indices: []string{"movies"}, + Body: strings.NewReader(`{"properties":{ "director":{"type":"text"}}}`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Mappings updated: %t\n", mappingPutResp.Acknowledged) ``` ### Get Metadata for an Index -Let's check if the index's settings and mappings have been updated by using the `indices.get` API action: +Let's check if the index's settings and mappings have been updated by using the `client.Indices.Get()` action: ```go - res, err := client.Indices.Get([]string{movies}) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", res) + getResp, err := client.Indices.Get( + ctx, + opensearchapi.IndicesGetReq{ + Indices: []string{"movies"}, + }, + ) + if err != nil { + return err + } + // Json Marshal the struct to pretty print + respAsJson, err := json.MarshalIndent(getResp.Indices, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", string(respAsJson)) ``` The response body contains the index's settings and mappings: @@ -184,30 +222,36 @@ The response body contains the index's settings and mappings: ### Delete an Index -Let's delete the `movies` index by using the `indices.delete` API action: +Let's delete the `movies` index by using the `client.Indices.Delete()` action: ```go - deleteIndexes, err := client.Indices.Delete([]string{movies}) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", deleteIndexes) + delResp, err := client.Indices.Delete(ctx, opensearchapi.IndicesDeleteReq{Indices: []string{"movies"}}) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) ``` We can also delete multiple indices at once: ```go - deleteIndexes, err := client.Indices.Delete( - []string{movies, "burner", "paintings"}, - client.Indices.Delete.WithIgnoreUnavailable(true), - ) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", deleteIndexes) + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"movies", "paintings", "burner"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) + + return nil +} ``` -Notice that we are passing `ignore unavailable` to the request. This tells the client to ignore the `404` error if the index doesn't exist for deletion. Without it, the above `delete` request will throw an error because the `movies` index has already been deleted in the previous example. +Notice that we are passing `ignore unavailable` to the request. This tells the server to ignore the `404` error if the index doesn't exist for deletion. Without it, the above `delete` request will throw an error because the `movies` index has already been deleted in the previous example. ## Cleanup diff --git a/guides/index_template.md b/guides/index_template.md index f9e28a473..6f63af4f2 100644 --- a/guides/index_template.md +++ b/guides/index_template.md @@ -10,17 +10,43 @@ Assuming you have OpenSearch running locally on port 9200, you can create a clie package main import ( - "github.com/opensearch-project/opensearch-go/v2" - "log" + "context" + "crypto/tls" + "fmt" + "net/http" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" ) func main() { - client, err := opensearch.NewDefaultClient() - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", client) + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } } + +func example() error { + // Initialize the client with SSL/TLS enabled. + client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // For testing only. Use certificate for validation. + }, + Addresses: []string{"https://localhost:9200"}, + Username: "admin", // For testing only. Don't store credentials in code. + Password: "admin", + }, + }, + ) + if err != nil { + return err + } + + ctx := context.Background() ``` ## Index Template API Actions @@ -30,223 +56,233 @@ func main() { You can create an index template to define default settings and mappings for indices of certain patterns. The following example creates an index template named `books` with default settings and mappings for indices of the `books-*` pattern: ```go -body := strings.NewReader(`{ - "index_patterns": ["books-*"], - "template": { - "settings": { - "index": { - "number_of_shards": 3, - "number_of_replicas": 0 - } - }, - "mappings": { - "properties": { - "title": { "type": "text" }, - "author": { "type": "text" }, - "published_on": { "type": "date" }, - "pages": { "type": "integer" } - } - } - } -}`) - -res, err := client.Indices.PutIndexTemplate("books", body) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + tempCreateResp, err := client.IndexTemplate.Create( + ctx, + opensearchapi.IndexTemplateCreateReq{ + IndexTemplate: "books", + Body: strings.NewReader(`{ + "index_patterns": ["books-*"], + "template": { + "settings": { + "index": { + "number_of_shards": 3, + "number_of_replicas": 0 + } + }, + "mappings": { + "properties": { + "title": { "type": "text" }, + "author": { "type": "text" }, + "published_on": { "type": "date" }, + "pages": { "type": "integer" } + } + } + }, + "priority": 50 + }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Index Tempalte created: %t\n", tempCreateResp.Acknowledged) ``` Now, when you create an index that matches the `books-*` pattern, OpenSearch will automatically apply the template's settings and mappings to the index. Let's create an index named `books-nonfiction` and verify that its settings and mappings match those of the template: ```go -res, err = client.Indices.Create("books-nonfiction") -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -// check mappings properties -res, err = client.Indices.Get([]string{"books-nonfiction"}) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + fmt.Printf("Index Tempalte created: %t\n", tempCreateResp.Acknowledged) + + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: "books-nonfiction"}) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) + + getResp, err := client.Indices.Get(ctx, opensearchapi.IndicesGetReq{Indices: []string{"books-nonfiction"}}) + if err != nil { + return err + } + respAsJson, err := json.MarshalIndent(getResp.Indices, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", string(respAsJson)) ``` ### Multiple Index Templates -If multiple index templates match the index's name, OpenSearch will apply the template with the highest priority. The following example creates two index templates named `books-*` and `books-fiction-*` with different settings: +If multiple index templates match the index's name, OpenSearch will apply the template with the highest priority. The following example creates one more index templates named `books-fiction` with different settings: ```go -res, err := client.Indices.PutIndexTemplate("books", strings.NewReader(`{ - "index_patterns": ["books-*"], - "priority": 0, - "template": { - "settings": { - "index": { - "number_of_shards": 3, - "number_of_replicas": 0 - } - } - } -}`)) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -// higher priority than the `books` template -res, err = client.Indices.PutIndexTemplate("books-fiction", strings.NewReader(`{ - "index_patterns": ["books-fiction-*"], - "priority": 1, - "template": { - "settings": { - "index": { - "number_of_shards": 1, - "number_of_replicas": 1 - } - } - } -}`)) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + // higher priority than the `books` template + tempCreateResp, err = client.IndexTemplate.Create( + ctx, + opensearchapi.IndexTemplateCreateReq{ + IndexTemplate: "books-fiction", + Body: strings.NewReader(`{ + "index_patterns": ["books-fiction-*"], + "template": { + "settings": { + "index": { + "number_of_shards": 1, + "number_of_replicas": 0 + } + } + }, + "priority": 60 + }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Index Tempalte created: %t\n", tempCreateResp.Acknowledged) ``` -When we create an index named `books-fiction-romance`, OpenSearch will apply the `books-fiction-*` template's settings to the index: +When we create an index named `books-fiction-romance`, OpenSearch will apply the `books-fiction` template's settings to the index: ```go -res, err = client.Indices.Create("books-fiction-romance") -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + createResp, err = client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: "books-fiction-romance"}) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) + + getResp, err = client.Indices.Get(ctx, opensearchapi.IndicesGetReq{Indices: []string{"books-fiction-romance"}}) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(getResp.Indices, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", string(respAsJson)) +``` -res, err = client.Indices.Get([]string{"books-fiction-romance"}) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) +Let us clean up the created templates and indices: + +```go + delTempResp, err := client.IndexTemplate.Delete(ctx, opensearchapi.IndexTemplateDeleteReq{IndexTemplate: "books*"}) + if err != nil { + return err + } + fmt.Printf("Deleted templates: %t\n", delTempResp.Acknowledged) + + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"books-*"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted indices: %t\n", delResp.Acknowledged) ``` -### Composable Index Templates +### Component Templates -Composable index templates are a new type of index template that allow you to define multiple component templates and compose them into a final template. The following example creates a component template named `books_mappings` with default mappings for indices of the `books-*` and `books-fiction-*` patterns: +Component templates are subsets of templates that can be used by index templates. This allows you do store duplicate index template parts in a Component template and reuse it across index templates. The following example creates a component template named `books` with default mappings and an index template with a `books-*` patterns referencing the component template: ```go -// delete index templates if they exist -res, err := client.Indices.DeleteIndexTemplate("books-*") -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -// delete indices if they exist -res, err = client.Indices.Delete([]string{"books-*", "books-fiction-*"}) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -// Composable Index Templates -res, err = client.Cluster.PutComponentTemplate("books_mappings", strings.NewReader(`{ - "template": { - "mappings": { - "properties": { - "title": { "type": "text" }, - "author": { "type": "text" }, - "published_on": { "type": "date" }, - "pages": { "type": "integer" } - } - } - } -}`)) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -// use the `books_mappings` component template with priority 0 -res, err = client.Indices.PutIndexTemplate("books", strings.NewReader(`{ - "index_patterns": ["books-*"], - "composed_of": ["books_mappings"], - "priority": 0, - "template": { - "settings": { - "index": { - "number_of_shards": 3, - "number_of_replicas": 0 - } - } - } -}`)) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -// use the `books_mappings` component template with priority 1 -res, err = client.Indices.PutIndexTemplate("books", strings.NewReader(`{ - "index_patterns": ["books-fiction-*"], - "composed_of": ["books_mappings"], - "priority": 1, - "template": { - "settings": { - "index": { - "number_of_shards": 3, - "number_of_replicas": 0 - } - } - } -}`)) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + // Component templates + compTempCreateResp, err := client.ComponentTemplate.Create( + ctx, + opensearchapi.ComponentTemplateCreateReq{ + ComponentTemplate: "books", + Body: strings.NewReader(`{ + "template": { + "mappings": { + "properties": { + "title": { "type": "text" }, + "author": { "type": "text" }, + "published_on": { "type": "date" }, + "pages": { "type": "integer" } + } + } + } + }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", compTempCreateResp.Acknowledged) + + // Index template composed of books component template + tempCreateResp, err := client.IndexTemplate.Create( + ctx, + opensearchapi.IndexTemplateCreateReq{ + IndexTemplate: "books", + Body: strings.NewReader(`{ + "index_patterns": ["books-*"], + "template": { + "settings": { + "index": { + "number_of_shards": 3, + "number_of_replicas": 0 + } + } + }, + "composed_of": ["books"], + "priority": 50 + }`), + }, + ) + if err != nil { + return err + } + fmt.Printf("Index Tempalte created: %t\n", tempCreateResp.Acknowledged) ``` -When we create an index named `books-fiction-horror`, OpenSearch will apply the `books-fiction-*` template's settings, and `books_mappings` template mappings to the index: +When we create an index named `books-fiction-horror`, OpenSearch will apply the `books` index template settings, and `books` component template mappings to the index: ```go -res, err = client.Indices.Create("books-fiction-horror") -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) - -res, err = client.Indices.Get([]string{"books-fiction-horror"}) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + createResp, err = client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: "books-fiction-horror"}) + if err != nil { + return err + } + fmt.Printf("Index created: %t\n", createResp.Acknowledged) + + getResp, err = client.Indices.Get(ctx, opensearchapi.IndicesGetReq{Indices: []string{"books-fiction-horror"}}) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(getResp.Indices, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Document:\n%s\n", string(respAsJson)) ``` ### Get an Index Template -You can get an index template with the `get_index_template` API action: +You can get an index template with the `IndexTemplate.Get()` action: ```go -res, err = client.Indices.GetIndexTemplate( - client.Indices.GetIndexTemplate.WithName("books"), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + indexTempGetReq, err := client.IndexTemplate.Get(ctx, &opensearchapi.IndexTemplateGetReq{IndexTemplates: []string{"books"}}) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(indexTempGetReq, "", " ") + if err != nil { + return err + } + fmt.Printf("Get Index Template:\n%s\n", string(respAsJson)) ``` ### Delete an Index Template -You can delete an index template with the `delete_template` API action: +You can delete an index template with the `IndexTemplate.Delete()` action: ```go -res, err = client.Indices.DeleteIndexTemplate("books") -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + delTempResp, err = client.IndexTemplate.Delete(ctx, opensearchapi.IndexTemplateDeleteReq{IndexTemplate: "books*"}) + if err != nil { + return err + } + fmt.Printf("Deleted templates: %t\n", delTempResp.Acknowledged) ``` ## Cleanup @@ -254,9 +290,24 @@ log.Printf("response: [%+v]", res) Let's delete all resources created in this guide: ```go -res, err = client.Indices.DeleteIndexTemplate("books-fiction") -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) + delResp, err = client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"books-*"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted indices: %t\n", delResp.Acknowledged) + + compTempDelResp, err := client.ComponentTemplate.Delete(ctx, opensearchapi.ComponentTemplateDeleteReq{ComponentTemplate: "books*"}) + if err != nil { + return err + } + fmt.Printf("Deleted templates: %t\n", compTempDelResp.Acknowledged) + + return nil } -log.Printf("response: [%+v]", res) ``` diff --git a/guides/search.md b/guides/search.md index e2b4fe2e0..9cb509f50 100644 --- a/guides/search.md +++ b/guides/search.md @@ -10,66 +10,77 @@ Let's start by creating an index and adding some documents to it: package main import ( - "context" - "fmt" - "github.com/opensearch-project/opensearch-go/v2" - "github.com/opensearch-project/opensearch-go/v2/opensearchapi" - "log" - "strings" + "context" + "fmt" + "os" + "strconv" + "strings" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" ) func main() { - client, err := opensearch.NewDefaultClient() - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", client) - - movies := "movies" - - // create the index - createMovieIndex, err := client.Indices.Create(movies) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - log.Printf("response: [%+v]", createMovieIndex) - - for i := 1; i < 11; i++ { - req := opensearchapi.IndexRequest{ - Index: movies, - DocumentID: fmt.Sprintf("%d", i), - Body: strings.NewReader(fmt.Sprintf(`{"title": "The Dark Knight %d", "director": "Christopher Nolan", "year": %d}`, i, 2008+i)), - } - _, err := req.Do(context.Background(), client) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - } - - req := opensearchapi.IndexRequest{ - Index: movies, - Body: strings.NewReader(`{"title": "The Godfather", "director": "Francis Ford Coppola", "year": 1972}`), - } - _, err = req.Do(context.Background(), client) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - - req = opensearchapi.IndexRequest{ - Index: movies, - Body: strings.NewReader(`{"title": "The Shawshank Redemption", "director": "Frank Darabont", "year": 1994}`), - } - _, err = req.Do(context.Background(), client) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } - - // refresh the index to make the documents searchable - _, err = client.Indices.Refresh(client.Indices.Refresh.WithIndex(movies)) - if err != nil { - log.Printf("error occurred: [%s]", err.Error()) - } + if err := example(); err != nil { + fmt.Println(fmt.Sprintf("Error: %s", err)) + os.Exit(1) + } } + +func example() error { + client, err := opensearchapi.NewDefaultClient() + if err != nil { + return err + } + + ctx := context.Background() + exampleIndex := "movies" + + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{Index: exampleIndex}) + if err != nil { + return err + } + fmt.Printf("Created: %t\n", createResp.Acknowledged) + + for i := 1; i < 11; i++ { + _, err = client.Index( + ctx, + opensearchapi.IndexReq{ + Index: exampleIndex, + DocumentID: strconv.Itoa(i), + Body: strings.NewReader(fmt.Sprintf(`{"title": "The Dark Knight %d", "director": "Christopher Nolan", "year": %d}`, i, 2008+i)), + }, + ) + if err != nil { + return err + } + } + + _, err = client.Index( + ctx, + opensearchapi.IndexReq{ + Index: exampleIndex, + Body: strings.NewReader(`{"title": "The Godfather", "director": "Francis Ford Coppola", "year": 1972}`), + }, + ) + if err != nil { + return err + } + + _, err = client.Index( + ctx, + opensearchapi.IndexReq{ + Index: exampleIndex, + Body: strings.NewReader(`{"title": "The Shawshank Redemption", "director": "Frank Darabont", "year": 1994}`), + }, + ) + if err != nil { + return err + } + + _, err = client.Indices.Refresh(ctx, &opensearchapi.IndicesRefreshReq{Indices: []string{exampleIndex}}) + if err != nil { + return err + } ``` ## Search API @@ -79,26 +90,35 @@ func main() { The search API allows you to search for documents in an index. The following example searches for ALL documents in the `movies` index: ```go -res, err := client.Search( - client.Search.WithIndex(movies), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", res) + searchResp, err := client.Search(ctx, &opensearchapi.SearchReq{Indices: []string{exampleIndex}}) + if err != nil { + return err + } + respAsJson, err := json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) ``` You can also search for documents that match a specific query. The following example searches for documents that match the query `dark knight`: ```go -part, err := client.Search( - client.Search.WithIndex(movies), - client.Search.WithQuery(`title: "dark knight"`), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", part) + searchResp, err = client.Search( + ctx, + &opensearchapi.SearchReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.SearchParams{Query: `title: "dark knight"`}, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) ``` OpenSearch query DSL allows you to specify complex queries. Check out the [OpenSearch query DSL documentation](https://opensearch.org/docs/latest/query-dsl/) for more information. @@ -108,17 +128,26 @@ OpenSearch query DSL allows you to specify complex queries. Check out the [OpenS The search API allows you to paginate through the search results. The following example searches for documents that match the query `dark knight`, sorted by `year` in ascending order, and returns the first 2 results after skipping the first 5 results: ```go -sort, err := client.Search( - client.Search.WithIndex(movies), - client.Search.WithSize(2), - client.Search.WithFrom(5), - client.Search.WithSort("year:desc"), - client.Search.WithQuery(`title: "dark knight"`), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", sort) + searchResp, err = client.Search( + ctx, + &opensearchapi.SearchReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.SearchParams{ + Query: `title: "dark knight"`, + Size: opensearchapi.ToPointer(2), + From: opensearchapi.ToPointer(5), + Sort: []string{"year:desc"}, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) ``` ### Pagination with scroll @@ -126,17 +155,26 @@ log.Printf("response: [%+v]", sort) When retrieving large amounts of non-real-time data, you can use the `scroll` parameter to paginate through the search results. ```go -page1, err := client.Search( - client.Search.WithIndex(movies), - client.Search.WithSize(2), - client.Search.WithQuery(`title: "dark knight"`), - client.Search.WithSort("year:asc"), - client.Search.WithScroll(time.Minute), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", page1) + searchResp, err = client.Search( + ctx, + &opensearchapi.SearchReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.SearchParams{ + Query: `title: "dark knight"`, + Size: opensearchapi.ToPointer(2), + Sort: []string{"year:desc"}, + Scroll: time.Minute, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) ``` ### Pagination with Point in Time @@ -144,44 +182,59 @@ log.Printf("response: [%+v]", page1) The scroll example above has one weakness: if the index is updated while you are scrolling through the results, they will be paginated inconsistently. To avoid this, you should use the "Point in Time" feature. The following example demonstrates how to use the `point_in_time` and `pit_id` parameters to paginate through the search results: ```go -// create a point in time -_, pit, err := client.PointInTime.Create( - client.PointInTime.Create.WithIndex(movies), - client.PointInTime.Create.WithKeepAlive(time.Minute), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("created pit: [%+v]", pit) - -// run a search query with a pit.id -page1, err := client.Search( - client.Search.WithSize(5), - client.Search.WithBody(strings.NewReader(fmt.Sprintf(`{ "pit": { "id": "%s", "keep_alive": "1m" } }`, pit.PitID))), - client.Search.WithSort("year:asc"), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", page1) - -// to get the next set of documents, run the same query with the last document’s sort values as the search_after parameter, keeping the same sort and pit.id. -page2, err := client.Search( - client.Search.WithSize(5), - client.Search.WithBody(strings.NewReader(fmt.Sprintf(`{ "pit": { "id": "%s", "keep_alive": "1m" }, "search_after": [ "1994" ] }`, pit.PitID))), - client.Search.WithSort("year:asc"), -) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("response: [%+v]", page2) - -// to delete the point in time, run the following query -_, delpits, err := client.PointInTime.Delete(client.PointInTime.Delete.WithPitID(pit.PitID)) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("deleted pits: [%+v]", delpits) + pitCreateResp, err := client.PointInTime.Create( + ctx, + opensearchapi.PointInTimeCreateReq{ + Indices: []string{exampleIndex}, + Params: opensearchapi.PointInTimeCreateParams{KeepAlive: time.Minute}, + }, + ) + if err != nil { + return err + } + + searchResp, err = client.Search( + ctx, + &opensearchapi.SearchReq{ + Body: strings.NewReader(fmt.Sprintf(`{ "pit": { "id": "%s", "keep_alive": "1m" } }`, pitCreateResp.PitID)), + Params: opensearchapi.SearchParams{ + Size: opensearchapi.ToPointer(5), + Sort: []string{"year:desc"}, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) + + searchResp, err = client.Search( + ctx, + &opensearchapi.SearchReq{ + Body: strings.NewReader(fmt.Sprintf(`{ "pit": { "id": "%s", "keep_alive": "1m" }, "search_after": [ "1994" ] }`, pitCreateResp.PitID)), + Params: opensearchapi.SearchParams{ + Size: opensearchapi.ToPointer(5), + Sort: []string{"year:desc"}, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(searchResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Search Response:\n%s\n", string(respAsJson)) + + _, err = client.PointInTime.Delete(ctx, opensearchapi.PointInTimeDeleteReq{PitID: []string{pitCreateResp.PitID}}) + if err != nil { + return err + } ``` Note that a point-in-time is associated with an index or a set of index. So, when performing a search with a point-in-time, you DO NOT specify the index in the search. @@ -191,43 +244,84 @@ Note that a point-in-time is associated with an index or a set of index. So, whe The source API returns the source of the documents with included or excluded fields. The following example returns all fields from document source in the `movies` index: ```go -getSourceRequest := opensearchapi.GetSourceRequest{ - Index: "movies", - DocumentID: "1", -} -getSourceResponse, err := getSourceRequest.Do(context.Background(), client) -if err != nil { - log.Printf("error occurred: [%s]", err.Error()) -} -log.Printf("source: [%+v]", getSourceResponse) + sourceResp, err := client.Document.Source( + ctx, + opensearchapi.DocumentSourceReq{ + Index: "movies", + DocumentID: "1", + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(sourceResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Source Response:\n%s\n", string(respAsJson)) ``` To include certain fields in the source response, use `SourceIncludes` or `Source`(this field is deprecated and `SourceIncludes` is recommended to be used instead). To get only required fields: ```go -getSourceRequest = opensearchapi.GetSourceRequest{ - Index: "movies", - DocumentID: "1", - SourceIncludes: []string{"title"}, -} + sourceResp, err := client.Document.Source( + ctx, + opensearchapi.DocumentSourceReq{ + Index: "movies", + DocumentID: "1", + Params: opensearchapi.DocumentSourceParams{ + SourceIncludes: []string{"title"}, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(sourceResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Source Response:\n%s\n", string(respAsJson)) ``` To exclude certain fields in the source response, use `SourceExcludes` as follows: ```go -getSourceRequest = opensearchapi.GetSourceRequest{ - Index: "movies", - DocumentID: "1", - SourceExcludes: []string{"title"}, -} + sourceResp, err = client.Document.Source( + ctx, + opensearchapi.DocumentSourceReq{ + Index: "movies", + DocumentID: "1", + Params: opensearchapi.DocumentSourceParams{ + SourceExcludes: []string{"title"}, + }, + }, + ) + if err != nil { + return err + } + respAsJson, err = json.MarshalIndent(sourceResp, "", " ") + if err != nil { + return err + } + fmt.Printf("Source Response:\n%s\n", string(respAsJson)) ``` ## Cleanup ```go -deleteIndex, err := client.Indices.Delete([]string{"movies"}) -if err != nil { - log.Printf("Error creating index: %s", err.Error()) + delResp, err := client.Indices.Delete( + ctx, + opensearchapi.IndicesDeleteReq{ + Indices: []string{"movies"}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + if err != nil { + return err + } + fmt.Printf("Deleted: %t\n", delResp.Acknowledged) + + return nil } -log.Printf("response: [%+v]", deleteIndex) ``` diff --git a/internal/build/cmd/generate/commands/genexamples/command.go b/internal/build/cmd/generate/commands/genexamples/command.go deleted file mode 100644 index 81a9ddb91..000000000 --- a/internal/build/cmd/generate/commands/genexamples/command.go +++ /dev/null @@ -1,472 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package genexamples - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "regexp" - "strings" - "time" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd" - - "github.com/spf13/cobra" - "golang.org/x/tools/imports" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) - -var ( - inputSrc *string - outputSrc *string - debugSrc *bool - colorSrc *bool - gofmtSrc *bool - - inputDoc *string - outputDoc *string - debugDoc *bool -) - -func init() { - inputSrc = genexamplesSrcCmd.Flags().StringP("input", "i", "", "Path to a file with specification for examples") - outputSrc = genexamplesSrcCmd.Flags().StringP("output", "o", "", "Path to a folder for generated output") - debugSrc = genexamplesSrcCmd.Flags().BoolP("debug", "d", false, "Print the generated source to terminal") - colorSrc = genexamplesSrcCmd.Flags().BoolP("color", "c", true, "Syntax highlight the debug output") - gofmtSrc = genexamplesSrcCmd.Flags().BoolP("gofmt", "f", true, "Format generated output with 'gofmt'") - - genexamplesSrcCmd.MarkFlagRequired("input") - genexamplesSrcCmd.MarkFlagRequired("output") - genexamplesSrcCmd.Flags().SortFlags = false - - inputDoc = genexamplesDocCmd.Flags().StringP("input", "i", "", "Path to a file with specification for examples") - outputDoc = genexamplesDocCmd.Flags().StringP("output", "o", "", "Path to a folder for generated output") - debugDoc = genexamplesDocCmd.Flags().BoolP("debug", "d", false, "Print the generated source to terminal") - - genexamplesDocCmd.MarkFlagRequired("input") - genexamplesDocCmd.MarkFlagRequired("output") - genexamplesDocCmd.Flags().SortFlags = false - - genexamplesCmd.AddCommand(genexamplesSrcCmd) - genexamplesCmd.AddCommand(genexamplesDocCmd) - - cmd.RegisterCmd(genexamplesCmd) -} - -var genexamplesCmd = &cobra.Command{ - Use: "examples", - Short: "Generate the Go examples for documentation", -} - -var genexamplesSrcCmd = &cobra.Command{ - Use: "src", - Short: "Generate the Go sources for examples", - Run: func(cmd *cobra.Command, args []string) { - command := &SrcCommand{ - Input: *inputSrc, - Output: *outputSrc, - DebugSource: *debugSrc, - ColorizeSource: *colorSrc, - GofmtSource: *gofmtSrc, - } - if err := command.Execute(); err != nil { - utils.PrintErr(err) - os.Exit(1) - } - }, -} - -var genexamplesDocCmd = &cobra.Command{ - Use: "doc", - Short: "Generate the ASCIIDoc examples", - Run: func(cmd *cobra.Command, args []string) { - command := &DocCommand{Input: *inputDoc, Output: *outputDoc, DebugSource: *debugDoc} - if err := command.Execute(); err != nil { - utils.PrintErr(err) - os.Exit(1) - } - }, -} - -// SrcCommand represents the command for generating Go source code. -// -type SrcCommand struct { - Input string - Output string - DebugSource bool - ColorizeSource bool - GofmtSource bool -} - -// DocCommand represents the command for generating ASCIIDoc examples. -// -type DocCommand struct { - Input string - Output string - DebugSource bool -} - -// Execute runs the command. -// -func (cmd *SrcCommand) Execute() error { - var ( - processed int - skipped int - translated int - start = time.Now() - seen = make(map[string]bool) - ) - - if cmd.Output != "-" { - outputDir := filepath.Join(cmd.Output, "src") - if err := os.MkdirAll(outputDir, 0775); err != nil { - return fmt.Errorf("error creating output directory %q: %s", outputDir, err) - } - } - - f, err := os.Open(cmd.Input) - if err != nil { - return fmt.Errorf("error reading input: %s", err) - } - defer f.Close() - - var examples []Example - if err := json.NewDecoder(f).Decode(&examples); err != nil { - return fmt.Errorf("error decoding input: %s", err) - } - - for _, e := range examples { - if !e.IsEnabled() || !e.IsExecutable() { - skipped++ - continue - } - - if seen[e.Digest] { - continue - } - - var shouldSkip bool - for _, pat := range skipPatterns { - matched, _ := regexp.MatchString(pat, e.Source) - if matched { - skipped++ - shouldSkip = true - } - } - if shouldSkip { - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintf(os.Stderr, "Skipping example %q @ %s\n", e.ID(), e.Digest) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - skipped++ - continue - } - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintf(os.Stderr, "Processing example %q @ %s\n", e.ID(), e.Digest) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - if err := cmd.processExample(e); err != nil { - return fmt.Errorf("error processing example %s: %v", e.ID(), err) - } - processed++ - if e.IsTranslated() { - translated++ - } - seen[e.Digest] = true - } - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintf( - os.Stderr, - "Processed %d examples, translated %d, skipped %d examples in %s\n", - processed, - translated, - skipped, - time.Since(start).Truncate(time.Millisecond)) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - - return nil -} - -func (cmd *SrcCommand) processExample(e Example) error { - g := SrcGenerator{Example: e} - fName := filepath.Join(cmd.Output, "src", g.Filename()) - out, err := g.Output() - if err != nil { - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintln(os.Stderr, e.Source) - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - return err - } - - if cmd.GofmtSource { - var buf bytes.Buffer - buf.ReadFrom(out) - - bout, err := imports.Process( - "example_test.go", - buf.Bytes(), - &imports.Options{ - AllErrors: true, - Comments: true, - FormatOnly: false, - TabIndent: true, - TabWidth: 1, - }) - if err != nil { - if cmd.DebugSource { - utils.PrintSourceWithErr(&buf, err) - } - return err - } - - out = bytes.NewBuffer(bout) - } - - if cmd.DebugSource { - var ( - err error - buf bytes.Buffer - src io.Reader - tee = io.TeeReader(out, &buf) - ) - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - - if cmd.ColorizeSource { - src, err = utils.Chromatize(tee) - if err != nil { - return fmt.Errorf("error syntax highligting the output: %s", err) - } - - _, err = io.Copy(os.Stderr, src) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - } - - if _, err = io.Copy(os.Stderr, tee); err != nil { - return fmt.Errorf("error copying output: %s", err) - } - - fmt.Fprintf(os.Stderr, "\n\n") - - out = &buf - } - - if cmd.Output == "-" { - if _, err := io.Copy(os.Stdout, out); err != nil { - return fmt.Errorf("error copying output: %s", err) - } - } else { - f, err := os.OpenFile(fName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) - if err != nil { - return fmt.Errorf("error creating file: %s", err) - } - if _, err = io.Copy(f, out); err != nil { - return fmt.Errorf("error copying output: %s", err) - } - if err := f.Close(); err != nil { - return fmt.Errorf("error closing file: %s", err) - } - } - - return nil -} - -// Execute runs the command. -// -func (cmd *DocCommand) Execute() error { - var ( - processed int - start = time.Now() - ) - - if cmd.Output != "-" { - outputDir := filepath.Join(cmd.Output, "doc") - if err := os.MkdirAll(outputDir, 0775); err != nil { - return fmt.Errorf("error creating output directory %q: %s", outputDir, err) - } - } - - files, err := ioutil.ReadDir(cmd.Input) - if err != nil { - return fmt.Errorf("failed to read input: %s", err) - } - - for _, fi := range files { - if !strings.HasSuffix(fi.Name(), ".go") { - continue - } - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintf(os.Stderr, "Processing file %s\n", fi.Name()) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - - f, err := os.Open(filepath.Join(cmd.Input, fi.Name())) - if err != nil { - return fmt.Errorf("error reading file: %s", err) - } - defer f.Close() - - if err := cmd.processFile(f); err != nil { - return fmt.Errorf("error processing file %q: %s", fi.Name(), err) - } - processed++ - } - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintf( - os.Stderr, - "Processed %d examples examples in %s\n", - processed, - time.Since(start).Truncate(time.Millisecond)) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - - return nil -} - -func (cmd *DocCommand) processFile(f *os.File) error { - var ( - src bytes.Buffer - - sc = bufio.NewScanner(f) - reBegin = regexp.MustCompile(`^\s?// tag:(\w+)\s?`) - reEnd = regexp.MustCompile(`^\s?// end:\w+\s?`) - reSkip = regexp.MustCompile(`// SKIP$`) - digest string - capture bool - outputFile string - ) - - for sc.Scan() { - line := sc.Text() - - if reBegin.MatchString(line) { - digest = reBegin.FindStringSubmatch(line)[1] - capture = true - } - if reEnd.MatchString(line) { - capture = false - } - - if capture && !reBegin.MatchString(line) && !reSkip.MatchString(line) { - line = strings.TrimPrefix(line, "\t") - src.WriteString(line) - src.WriteString("\n") - } - } - - if err := sc.Err(); err != nil { - return err - } - - out, err := DocGenerator{ - Source: &src, - Filename: filepath.Base(f.Name()), - Digest: digest, - }.Output() - if err != nil { - return fmt.Errorf("error generating output: %s", err) - } - - if cmd.DebugSource { - var buf bytes.Buffer - tee := io.TeeReader(out, &buf) - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - _, err = io.Copy(os.Stderr, tee) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - - out = &buf - } - - if cmd.Output == "-" { - if _, err := io.Copy(os.Stdout, out); err != nil { - return fmt.Errorf("error copying output: %s", err) - } - } else { - outputFile = filepath.Join(cmd.Output, "doc", digest+".asciidoc") - - f, err := os.OpenFile(outputFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) - if err != nil { - return fmt.Errorf("error creating file: %s", err) - } - if _, err = io.Copy(f, out); err != nil { - return fmt.Errorf("error copying output: %s", err) - } - if err := f.Close(); err != nil { - return fmt.Errorf("error closing file: %s", err) - } - } - - return nil -} diff --git a/internal/build/cmd/generate/commands/genexamples/generator.go b/internal/build/cmd/generate/commands/genexamples/generator.go deleted file mode 100644 index 709bc94ef..000000000 --- a/internal/build/cmd/generate/commands/genexamples/generator.go +++ /dev/null @@ -1,146 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package genexamples - -import ( - "bytes" - "fmt" - "io" - "strings" -) - -// SrcGenerator represents the generator for Go source files. -// -type SrcGenerator struct { - b bytes.Buffer - Example Example -} - -// DocGenerator represents the generator for Go source files. -// -type DocGenerator struct { - b bytes.Buffer - Source io.Reader - Filename string - Digest string -} - -func (g SrcGenerator) Filename() string { - return fmt.Sprintf( - "%s_%s_test.go", - strings.ReplaceAll(strings.TrimSuffix(g.Example.SourceLocation.File, ".asciidoc"), "/", "-"), - g.Example.Digest) -} - -func (g SrcGenerator) Output() (io.Reader, error) { - var out bytes.Buffer - - out.WriteString(`// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// Code generated, DO NOT EDIT - -package opensearch_test - -import ( - "fmt" - "os" - "testing" - - "github.com/opensearchproject/opensearch-go" -) - -var ( - _ = fmt.Printf - _ = os.Stdout - _ = opensearch.NewDefaultClient -) - -`) - - fmt.Fprintf(&out, "// <%s>\n//\n", g.Example.GithubURL()) - out.WriteString("// " + strings.Repeat("-", 80) + "\n") - for _, l := range strings.Split(g.Example.Source, "\n") { - out.WriteString("// " + l + "\n") - } - out.WriteString("// " + strings.Repeat("-", 80) + "\n\n") - - fmt.Fprintf(&out, `func Test_%s_%s(t *testing.T) {`+"\n", g.Example.Chapter(), g.Example.Digest) - out.WriteString("\t") - if !g.Example.IsTranslated() { - out.WriteString("// ") - } - out.WriteString(`client, _ := opensearch.NewDefaultClient()` + "\n") - - if !g.Example.IsTranslated() { - out.WriteString("\n\tt.Error(`Missing implementation for: ") - - out.WriteString(strings.Split(g.Example.Source, "\n")[0]) - out.WriteString("`)\n") - } else { - src, err := g.Example.Translated() - if err != nil { - return nil, err - } else { - out.WriteString(src) - } - } - - out.WriteString("}\n") - - return &out, nil -} - -func (g DocGenerator) Output() (io.Reader, error) { - var out bytes.Buffer - - fmt.Fprintf(&out, "// Generated from %s\n//\n", g.Filename) - - out.WriteString("[source, go]\n----\n") - - _, err := out.ReadFrom(g.Source) - if err != nil { - return nil, err - } - - out.WriteString("----\n") - - return &out, nil -} diff --git a/internal/build/cmd/generate/commands/genexamples/model.go b/internal/build/cmd/generate/commands/genexamples/model.go deleted file mode 100644 index 46aa838da..000000000 --- a/internal/build/cmd/generate/commands/genexamples/model.go +++ /dev/null @@ -1,214 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package genexamples - -import ( - "bufio" - "fmt" - "regexp" - "sort" - "strings" -) - -func init() { - sort.Strings(EnabledFiles) -} - -// EnabledFiles contains a list of files where documentation should be generated. -// -var EnabledFiles = []string{ - "aggregations/bucket/datehistogram-aggregation.asciidoc", - "aggregations/bucket/filter-aggregation.asciidoc", - "aggregations/bucket/terms-aggregation.asciidoc", - "aggregations/metrics/valuecount-aggregation.asciidoc", - "api-conventions.asciidoc", - "cat/indices.asciidoc", - "cluster/health.asciidoc", - "docs/bulk.asciidoc", - "docs/delete-by-query.asciidoc", - "docs/delete.asciidoc", - "docs/get.asciidoc", - "docs/index_.asciidoc", - "docs/reindex.asciidoc", - "docs/update-by-query.asciidoc", - "docs/update.asciidoc", - "getting-started.asciidoc", - "indices/aliases.asciidoc", - "indices/create-index.asciidoc", - "indices/delete-index.asciidoc", - "indices/get-index.asciidoc", - "indices/get-mapping.asciidoc", - "indices/put-mapping.asciidoc", - "indices/templates.asciidoc", - "indices/update-settings.asciidoc", - "mapping.asciidoc", - "mapping/fields/id-field.asciidoc", - "mapping/params/fielddata.asciidoc", - "mapping/params/format.asciidoc", - "mapping/params/multi-fields.asciidoc", - "mapping/types/array.asciidoc", - "mapping/types/date.asciidoc", - "mapping/types/keyword.asciidoc", - "mapping/types/nested.asciidoc", - "mapping/types/numeric.asciidoc", - "query-dsl.asciidoc", - "query-dsl/bool-query.asciidoc", - "query-dsl/exists-query.asciidoc", - "query-dsl/function-score-query.asciidoc", - "query-dsl/match-all-query.asciidoc", - "query-dsl/match-phrase-query.asciidoc", - "query-dsl/match-query.asciidoc", - "query-dsl/multi-match-query.asciidoc", - "query-dsl/nested-query.asciidoc", - "query-dsl/query-string-query.asciidoc", - "query-dsl/query_filter_context.asciidoc", - "query-dsl/range-query.asciidoc", - "query-dsl/regexp-query.asciidoc", - "query-dsl/term-query.asciidoc", - "query-dsl/terms-query.asciidoc", - "query-dsl/wildcard-query.asciidoc", - "search.asciidoc", - "search/count.asciidoc", - "search/request-body.asciidoc", - "search/request/from-size.asciidoc", - "search/request/scroll.asciidoc", - "search/request/sort.asciidoc", - "search/search.asciidoc", - "search/suggesters.asciidoc", - "setup/install/check-running.asciidoc", - "setup/logging-config.asciidoc", -} - -var ( - reHTTPMethod = regexp.MustCompile(`^HEAD|GET|PUT|DELETE|POST`) - reAnnotation = regexp.MustCompile(`^(?P.*)\s*\<\d\>\s*$`) - reComment = regexp.MustCompile(`^#\s?`) -) - -// Example represents the code example in documentation. -// -type Example struct { - SourceLocation struct { - File string - Line int - } `json:"source_location"` - - Digest string - Source string -} - -// IsEnabled returns true when the example should be processed. -// -func (e Example) IsEnabled() bool { - // TODO(karmi): Use "filepatch.Match()" to support glob patterns - - index := sort.SearchStrings(EnabledFiles, e.SourceLocation.File) - - if index > len(EnabledFiles)-1 || EnabledFiles[index] != e.SourceLocation.File { - return false - } - - return true -} - -// IsExecutable returns true when the example contains a request. -// -func (e Example) IsExecutable() bool { - return reHTTPMethod.MatchString(e.Source) -} - -// IsTranslated returns true when the example can be converted to Go source code. -// -func (e Example) IsTranslated() bool { - return Translator{Example: e}.IsTranslated() -} - -// ID returns example identifier. -// -func (e Example) ID() string { - return fmt.Sprintf("%s:%d", e.SourceLocation.File, e.SourceLocation.Line) -} - -// Chapter returns the example chapter. -// -func (e Example) Chapter() string { - r := strings.NewReplacer("/", "_", "-", "_", ".asciidoc", "") - return r.Replace(e.SourceLocation.File) -} - -// GithubURL returns a link for the example source. -// -func (e Example) GithubURL() string { - //TODO: fix url - return fmt.Sprintf("https://github.com/opensearch-project/documentation-website") -} - -// Commands returns the list of commands from source. -// -func (e Example) Commands() ([]string, error) { - var ( - buf strings.Builder - list []string - scan = bufio.NewScanner(strings.NewReader(e.Source)) - ) - - for scan.Scan() { - line := scan.Text() - - if reComment.MatchString(line) { - continue - } - - line = reAnnotation.ReplaceAllString(line, "$1") - - if reHTTPMethod.MatchString(line) { - if buf.Len() > 0 { - list = append(list, buf.String()) - } - buf.Reset() - } - - buf.WriteString(line) - buf.WriteString("\n") - } - - if err := scan.Err(); err != nil { - return list, err - } - - if buf.Len() > 0 { - list = append(list, buf.String()) - } - - return list, nil -} - -// Translated returns the code translated from Console to Go. -// -func (e Example) Translated() (string, error) { - return Translator{Example: e}.Translate() -} diff --git a/internal/build/cmd/generate/commands/genexamples/translator.go b/internal/build/cmd/generate/commands/genexamples/translator.go deleted file mode 100644 index 6d232677d..000000000 --- a/internal/build/cmd/generate/commands/genexamples/translator.go +++ /dev/null @@ -1,1701 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package genexamples - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "log" - "net/url" - "regexp" - "sort" - "strconv" - "strings" - "time" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) - -const testCheck = "\t" + `if err != nil { // SKIP - t.Fatalf("Error getting the response: %s", err) // SKIP - } // SKIP - defer res.Body.Close() // SKIP -` - -var _ = log.Print - -// ConsoleToGo contains translation rules. -// -var ConsoleToGo = []TranslateRule{ - - { // ----- Info() ----------------------------------------------------------- - Pattern: `^GET /\s*$`, - Func: func(in string) (string, error) { - return "res, err := client.Info()", nil - }}, - - { // ----- Cat.Health() ----------------------------------------------------- - Pattern: `^GET /?_cat/health\?v`, - Func: func(in string) (string, error) { - return "\tres, err := client.Cat.Health(client.Cat.Health.WithV(true))", nil - }}, - - { // ----- Cat.Indices() ----------------------------------------------------- - Pattern: `^GET /?_cat/indices`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^GET /?_cat/indices/?(?P[^/\s\?]+)?(?P\??[\S]+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - fmt.Fprint(&src, "\tres, err := client.Cat.Indices(\n") - - if matches[1] != "" { - fmt.Fprintf(&src, "\tes.Cat.Indices.WithIndex([]string{%q}...),\n", matches[1]) - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Cat.Indices", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Cluster.Health() ----------------------------------------------------- - Pattern: `^GET /?_cluster/health`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^(?PGET) /?_cluster/health/?(?P[^/\s\?]+)?(?P\??[\S]+)?\s*$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - fmt.Fprint(&src, "\tres, err := client.Cluster.Health(\n") - - if matches[2] != "" { - fmt.Fprintf(&src, "\tes.Cluster.Health.WithIndex([]string{%q}...),\n", matches[2]) - } - - if matches[3] != "" { - params, err := queryToParams(matches[3]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Cluster.Health", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Cluster.State() ----------------------------------------------------- - Pattern: `^GET /?_cluster/state`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^(?PGET) /?_cluster/state/?(?P[^/\s\?]+)?(?P\??[\S]+)?\s*$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - fmt.Fprint(&src, "\tres, err := client.Cluster.State(\n") - - if matches[2] != "" { - fmt.Fprintf(&src, "\tes.Cluster.State.WithIndex([]string{%q}...),\n", matches[2]) - } - - if matches[3] != "" { - params, err := queryToParams(matches[3]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Cluster.State", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Cluster.PutSettings() -------------------------------------------- - Pattern: `^PUT /?_cluster/settings`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^(?PPUT) /?_cluster/settings/?(?P\??[\S]+)?\s?(?P.*)`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - fmt.Fprint(&src, "\tres, err := client.Cluster.PutSettings(\n") - body, err := bodyStringToReader(matches[3]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\t%s", body) - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Cluster.PutSettings", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString(")") - return src.String(), nil - - }}, - - { // ----- Nodes.Stats() ----------------------------------------------------- - Pattern: `^GET /?_nodes/.*/?stats`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^(?PGET) /?_nodes/(?P[[:alnum:]]+)?/?stats/?(?P[^/\s\?]+)?/?(?P[^/\s?]+)?(?P\??[\S]+)?\s*$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - fmt.Println("matches") - for i, m := range matches { - fmt.Println(i, ":", m) - } - fmt.Fprint(&src, "\tres, err := client.Nodes.Stats(\n") - - if matches[2] != "" { - fmt.Fprintf(&src, "\tes.Nodes.Stats.WithNodeID([]string{%q}...),\n", matches[2]) - } - - if matches[3] != "" { - fmt.Fprintf(&src, "\tes.Nodes.Stats.WithMetric([]string{%q}...),\n", matches[3]) - } - - if matches[4] != "" { - fmt.Fprintf(&src, "\tes.Nodes.Stats.WithIndexMetric([]string{%q}...),\n", matches[4]) - } - - if matches[5] != "" { - params, err := queryToParams(matches[5]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Nodes.Stats", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- UpdateByQueryRethrottle() --------------------------------------------------------- - Pattern: `^POST /?_update_by_query.+_rethrottle`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^POST /?_update_by_query/(?P\S+)/_rethrottle(?P\??[\S/]+)?`) - - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.UpdateByQueryRethrottle(\n") - fmt.Fprintf(&src, "%q,\n", matches[1]) - if matches[2] != "" { - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[2], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - - var requestsPerSecond []string - for key, value := range params { - if key == "requests_per_second" { - requestsPerSecond = value - delete(params, key) - } - } - fmt.Fprintf(&src, "opensearchapi.IntPtr(%v),\n", strings.Join(requestsPerSecond, "")) - - args, err := paramsToArguments("UpdateByQueryRethrottle", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- UpdateByQuery() --------------------------------------------------------- - Pattern: `^(GET|POST) /?(\S+)?/?_update_by_query`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^(GET|POST) /?(?P[^/]*)?/?_update_by_query(?P\??[\S]+)?\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.UpdateByQuery(\n") - if matches[2] != "" { - fmt.Fprintf(&src, "\t[]string{%q},\n", matches[2]) - } - - if strings.TrimSpace(matches[4]) != "" { - body, err := bodyStringToReader(matches[4]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\tes.UpdateByQuery.WithBody(%s),\n", body) - } - - var params url.Values - if matches[3] != "" { - var err error - params, err = url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[3], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("UpdateByQuery", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprint(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- PutIngestPipeline() ------------------------------------------------------ - Pattern: `^PUT /?_ingest/pipeline.*`, - Func: func(in string) (string, error) { - var ( - src strings.Builder - ) - - re := regexp.MustCompile(`(?ms)^PUT /?_ingest/pipeline/(?P[^/\?\s]+)/?(?P\??[\S]+)?\s?(?P.*)`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Ingest.PutPipeline(\n") - fmt.Fprintf(&src, "\t%q,\n", matches[1]) - - if matches[3] != "" { - body, err := bodyStringToReader(matches[3]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\t%s,\n", body) - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Ingest.PutPipeline", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, "\t%s", args) - } - - src.WriteString(")") - return src.String(), nil - }, - }, - - { // ----- Index() or Create() ---------------------------------------------- - Pattern: `^(PUT|POST) /?.+/(_doc|_create|_update)/?.*`, - Func: func(in string) (string, error) { - var ( - src strings.Builder - apiName string - ) - - re := regexp.MustCompile(`(?ms)^(?PPUT|POST) /?(?P.+)/(?P_doc|_create|_update)/?(?P\w+)?(?P\??[\S]+)?\s?(?P.*)`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - switch matches[3] { - case "_doc": - apiName = "Index" - case "_create": - apiName = "Create" - case "_update": - apiName = "Update" - default: - return "", fmt.Errorf("Unknown API [%s]", matches[3]) - } - - src.WriteString("\tres, err := client." + apiName + "(\n") - - fmt.Fprintf(&src, "\t%q,\n", matches[2]) - - if apiName == "Create" || apiName == "Update" { - fmt.Fprintf(&src, "\t%q,\n", matches[4]) - } - - body, err := bodyStringToReader(matches[6]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\t%s,\n", body) - - if apiName == "Index" { - if matches[4] != "" { - fmt.Fprintf(&src, "\tes."+apiName+".WithDocumentID(%q),\n", matches[4]) - } - } - - if matches[5] != "" { - params, err := queryToParams(matches[5]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments(apiName, params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString("\tes." + apiName + ".WithPretty(),\n") - src.WriteString("\t)") - - return src.String(), nil - }}, - - { // ----- Indices.GetMapping() ------------------------------------------------- - Pattern: `^GET /?.*_mapping`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^GET /?(?P[^/\s]+)?(?P\??[\S/]+)?_mapping\s?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.GetMapping(") - if matches[1] != "" { - fmt.Fprintf(&src, "\tes.Indices.GetMapping.WithIndex(%q),\n", matches[1]) - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Indices.PutTemplate", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Indices.PutMapping() ------------------------------------------------- - Pattern: `^PUT /?[^/\s]+/_mapping`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^PUT /?(?P[^/\s]+)(?P\??[\S/]+)?_mapping\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.PutMapping(") - - if matches[2] != "" || matches[3] != "" { - fmt.Fprintf(&src, "\n\t[]string{%q},\n", matches[1]) - - if matches[3] != "" { - body, err := bodyStringToReader(matches[3]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\t%s,\n", body) - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Indices.PutMapping", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, "\t%s", args) - } - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Indices.GetSettings() ------------------------------------------------- - Pattern: `^GET /?[^/\s]+/_settings`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^GET /?(?P[^/\s]+)/_settings(?P\??[\S/]+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.GetSettings(") - - if matches[1] != "" { - fmt.Fprintf(&src, "\n\t\tes.Indices.GetSettings.WithIndex([]string{%q}...),\n", matches[1]) - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Indices.GetSettings", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, "\t\t%s", args) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Indices.PutSettings() ------------------------------------------------- - Pattern: `^PUT /?[^/\s]+/_settings`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^PUT /?(?P[^/\s]+)(?P\??[\S/]+)?_settings\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.PutSettings(") - - if matches[2] != "" || matches[3] != "" { - if matches[3] != "" { - body, err := bodyStringToReader(matches[3]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\t%s,\n", body) - } - - if matches[1] != "" { - fmt.Fprintf(&src, "\n\tes.Indices.PutSettings.WithIndex([]string{%q}...),\n", matches[1]) - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Indices.PutSettings", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, "\t%s", args) - } - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Indices.PutTemplate() ------------------------------------------------- - Pattern: `^PUT /?_template/[^/\s]+`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^PUT /?_template/(?P[^/\s]+)/?(?P\??[\S/]+)?\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.PutTemplate(") - fmt.Fprintf(&src, "\n\t%q,\n", matches[1]) - - if matches[2] != "" || matches[3] != "" { - if strings.TrimSpace(matches[3]) != "" { - body, err := bodyStringToReader(matches[3]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\t%s,\n", body) - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Indices.PutTemplate", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Indices.GetTemplate() ------------------------------------------------- - Pattern: `^GET /?_template/[^/\s]+`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^GET /?_template/(?P[^/\?\s]+)/?(?P\??[\S/]+)?\s?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.GetTemplate(") - if matches[1] != "" { - fmt.Fprintf(&src, "\n\tes.Indices.GetTemplate.WithName(%q),\n", matches[1]) - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Indices.GetTemplate", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Indices.Create() ------------------------------------------------- - Pattern: `^PUT /?[^/\s]+\s?`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^PUT /?(?P[^/\s]+)(?P\??[\S/]+)?\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.Create(") - if matches[2] != "" || matches[3] != "" { - fmt.Fprintf(&src, "\n\t%q,\n", matches[1]) - - if strings.TrimSpace(matches[3]) != "" { - body, err := bodyStringToReader(matches[3]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\tes.Indices.Create.WithBody(%s),\n", body) - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Indices.Create", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - } else { - fmt.Fprintf(&src, "%q", matches[1]) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- ClearScroll() --------------------------------------------------------- - Pattern: `^DELETE /?_search/scroll`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^DELETE /?_search/scroll/?(?P[[:alnum:]=_,]*)?(?P\??[\S]+)?\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.ClearScroll(\n") - - if strings.TrimSpace(matches[1]) != "" { - src.WriteString("\t\tes.ClearScroll.WithScrollID(") - scrollIDs := strings.Split(matches[1], ",") - for i, s := range scrollIDs { - fmt.Fprintf(&src, "%q", s) - if i < len(scrollIDs)-1 { - src.WriteString(",") - } - } - src.WriteString("),\n") - } - - if strings.TrimSpace(matches[3]) != "" { - body, err := bodyStringToReader(matches[3]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\t\tes.ClearScroll.WithBody(%s),\n", body) - } - - var params url.Values - if matches[2] != "" { - var err error - params, err = url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[2], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("ClearScroll", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprint(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- Delete() --------------------------------------------------------- - Pattern: `^DELETE /?\w+/_doc/\w+`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^DELETE /?(?P\w+)/_doc/(?P\w+)(?P\??\S+)?\s*$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - fmt.Fprint(&src, "\tres, err := client.Delete(") - - if matches[3] != "" { - fmt.Fprintf(&src, "\t%q,\n\t%q,\n", matches[1], matches[2]) - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[3], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Delete", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprint(&src, args) - - src.WriteString("\tclient.Delete.WithPretty(),\n") - } else { - fmt.Fprintf(&src, "\t%q, %q, client.Delete.WithPretty()", matches[1], matches[2]) - } - src.WriteString(")") - - return src.String(), nil - }}, - - { // ----- Indices.Delete() ------------------------------------------------- - Pattern: `^DELETE /?[^/\s]+[^_/]*`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^DELETE /?(?P[^/\s]+)(?P\??[\S/]+)?$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.Delete(") - - if matches[2] != "" { - fmt.Fprintf(&src, "\n\t[]string{%q},\n", matches[1]) - - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Indices.Delete", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } else { - fmt.Fprintf(&src, "[]string{%q}", matches[1]) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Indices.Refresh() ------------------------------------------------- - Pattern: `^GET /?[^/\s]*/?_refresh`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^GET /?(?P[^/\s]*)/?_refresh$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.Refresh(") - - if matches[1] != "" { - fmt.Fprintf(&src, "[]string{%q}", matches[1]) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Indices.Open() + Indices.Close() --------------------------------- - Pattern: `^POST /?[^/\s]*/?(?P_close|_open)\s*`, - Func: func(in string) (string, error) { - var src strings.Builder - var apiName string - - re := regexp.MustCompile(`(?ms)^POST /?(?P[^/\s]*)/?(?P_open|_close)\s*$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - switch matches[2] { - case "_open": - apiName = "Open" - case "_close": - apiName = "Close" - default: - return "", fmt.Errorf("unknown operation [%s]", matches[2]) - } - - fmt.Fprintf(&src, "\tres, err := client.Indices.%s(", apiName) - - if matches[1] != "" { - fmt.Fprintf(&src, "[]string{%q}", matches[1]) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Indices.Aliases() + Indices.PutAlias() --------------------------- - Pattern: `^POST /?[^/\s]*/?_aliases`, - Func: func(in string) (string, error) { - var src strings.Builder - var apiName string - - re := regexp.MustCompile(`(?ms)^POST /?(?P[^/\s]*)/?_aliases/?(?P\??[\S/]+)?\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - if matches[1] != "" { - apiName = "PutAlias" - src.WriteString("\tres, err := client.Indices.PutAlias(") - fmt.Fprintf(&src, "[]string{%q}", matches[1]) - } else { - apiName = "UpdateAliases" - src.WriteString("\tres, err := client.Indices.UpdateAliases(") - } - - if strings.TrimSpace(matches[3]) != "" { - body, err := bodyStringToReader(matches[3]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - if apiName == "PutAlias" { - fmt.Fprintf(&src, "\tes.Indices.%s.WithBody(%s),\n", apiName, body) - } else { - fmt.Fprintf(&src, "\t%s,\n", body) - } - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments(apiName, params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Indices.Forcemerge() ------------------------------------------------- - Pattern: `^POST /?[^/\s]*/?_forcemerge`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^POST /?(?P[^/\s]*)/?_forcemerge/?(?P\??[\S/]+)?$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.Forcemerge(") - - if matches[1] != "" { - fmt.Fprintf(&src, "\tclient.Indices.Forcemerge.WithIndex([]string{%q}...),\n", matches[1]) - } - - if matches[2] != "" { - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Indices.Forcemerge", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString(")") - return src.String(), nil - }}, - - { // ----- Get() or GetSource() --------------------------------------------- - Pattern: `^GET /?.+/(_doc|_source)/\w+`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^GET /?(?P.+)/(?P_doc|_source)/(?P\w+)(?P\??\S+)?\s*$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - var apiName string - switch matches[2] { - case "_doc": - apiName = "Get" - case "_source": - apiName = "GetSource" - default: - return "", fmt.Errorf("unknown API variant %q", matches[2]) - } - - if matches[4] == "" { - fmt.Fprintf(&src, "\tres, err := client."+apiName+"(%q, %q, client."+apiName+".WithPretty()", matches[1], matches[3]) - } else { - fmt.Fprintf(&src, "\tres, err := client."+apiName+"(\n\t%q,\n\t%q,\n\t", matches[1], matches[3]) - - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[4], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments(apiName, params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - - src.WriteString("\tes." + apiName + ".WithPretty(),\n") - } - - src.WriteString(")") - - return src.String(), nil - }}, - - { // ----- Exists() or ExistsSource() --------------------------------------- - Pattern: `^HEAD /?\w+/(_doc|_source)/\w+`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^HEAD /?(?P\w+)/(?P_doc|_source)/(?P\w+)(?P\??[\S]+)?\s*$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - var apiName string - switch matches[2] { - case "_doc": - apiName = "Exists" - case "_source": - apiName = "ExistsSource" - default: - return "", fmt.Errorf("unknown API variant %q", matches[2]) - } - - if matches[4] == "" { - fmt.Fprintf(&src, "\tres, err := client."+apiName+"(%q, %q, client."+apiName+".WithPretty()", matches[1], matches[2]) - } else { - fmt.Fprintf(&src, "\tres, err := client."+apiName+"(\n\t%q,\n\t%q,\n\t", matches[1], matches[2]) - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[4], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments(apiName, params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - - src.WriteString("\tes." + apiName + ".WithPretty(),\n") - } - - src.WriteString(")") - - return src.String(), nil - }}, - - { // ----- Scroll() --------------------------------------------------------- - Pattern: `^(GET|POST) /?_search/scroll`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^(GET|POST) /?_search/scroll(?P\??[\S]+)?\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Scroll(\n") - - if strings.TrimSpace(matches[3]) != "" { - body, err := bodyStringToReader(matches[3]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\tclient.Scroll.WithBody(%s),\n", body) - } - - var params url.Values - if matches[2] != "" { - var err error - params, err = url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[2], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Search", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprint(&src, args) - } - - var hasPretty bool - for k, _ := range params { - if k == "pretty" { - hasPretty = true - } - } - - if !hasPretty { - src.WriteString("\tclient.Scroll.WithPretty(),\n") - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- Search() --------------------------------------------------------- - Pattern: `^(GET|POST) /?[^/]*/?_search`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^(GET|POST) /?(?P[^/]*)?/?_search(?P\??[\S]+)?\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Search(\n") - if matches[2] != "" { - fmt.Fprintf(&src, "\tclient.Search.WithIndex(%q),\n", matches[2]) - } - - if strings.TrimSpace(matches[4]) != "" { - body, err := bodyStringToReader(matches[4]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\tes.Search.WithBody(%s),\n", body) - } - - var params url.Values - if matches[3] != "" { - var err error - params, err = url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[3], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Search", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprint(&src, args) - } - - var hasPretty bool - for k, _ := range params { - if k == "pretty" { - hasPretty = true - } - } - - if !hasPretty { - src.WriteString("\tclient.Search.WithPretty(),\n") - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- Count() --------------------------------------------------------- - Pattern: `^GET /?[^/]*/?_count`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^GET /?(?P[^/]*)?/?_count(?P\??[\S]+)?\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Count(\n") - if matches[1] != "" { - fmt.Fprintf(&src, "\tes.Count.WithIndex(%q),\n", matches[2]) - } - - if strings.TrimSpace(matches[3]) != "" { - body, err := bodyStringToReader(matches[3]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\tes.Count.WithBody(%s),\n", body) - } - - var params url.Values - if matches[2] != "" { - var err error - params, err = url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[2], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Count", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprint(&src, args) - } - - var hasPretty bool - for k, _ := range params { - if k == "pretty" { - hasPretty = true - } - } - - if !hasPretty { - src.WriteString("\tclient.Count.WithPretty(),\n") - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- DeleteByQueryRethrottle() --------------------------------------------------------- - Pattern: `^POST /?_delete_by_query.+_rethrottle`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^POST /?_delete_by_query/(?P\S+)/_rethrottle(?P\??[\S/]+)?`) - - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.DeleteByQueryRethrottle(\n") - fmt.Fprintf(&src, "%q,\n", matches[1]) - - if matches[2] != "" { - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[2], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - - var requestsPerSecond []string - for key, value := range params { - if key == "requests_per_second" { - requestsPerSecond = value - delete(params, key) - } - } - fmt.Fprintf(&src, "opensearchapi.IntPtr(%v),\n", strings.Join(requestsPerSecond, "")) - - args, err := paramsToArguments("DeleteByQueryRethrottle", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- DeleteByQuery() --------------------------------------------------------- - Pattern: `^(GET|POST) /?(\S+)?/?_delete_by_query`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^(GET|POST) /?(?P[^/]*)?/?_delete_by_query(?P\??[\S]+)?\s?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.DeleteByQuery(\n") - if matches[2] != "" { - fmt.Fprintf(&src, "\t[]string{%q},\n", matches[2]) - } - - if strings.TrimSpace(matches[4]) != "" { - body, err := bodyStringToReader(matches[4]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprintf(&src, "\t%s,\n", body) - } - - var params url.Values - if matches[3] != "" { - var err error - params, err = url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[3], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("DeleteByQuery", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprint(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- ReindexRethrottle() --------------------------------------------------------- - Pattern: `^POST /?_reindex.+_rethrottle`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^POST /?_reindex/(?P\S+)/_rethrottle(?P\??[\S/]+)?`) - - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.ReindexRethrottle(\n") - fmt.Fprintf(&src, "%q,\n", matches[1]) - - if matches[2] != "" { - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[2], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - - var requestsPerSecond []string - for key, value := range params { - if key == "requests_per_second" { - requestsPerSecond = value - delete(params, key) - } - } - fmt.Fprintf(&src, "opensearchapi.IntPtr(%v),\n", strings.Join(requestsPerSecond, "")) - - args, err := paramsToArguments("ReindexRethrottle", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- Reindex() --------------------------------------------------------- - Pattern: `^POST /?_reindex`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^POST /?_reindex(?P\??[\S/]+)?\s?(?P.+)?`) - - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Reindex(\n") - - if strings.TrimSpace(matches[2]) != "" { - body, err := bodyStringToReader(matches[2]) - if err != nil { - return "", fmt.Errorf("error converting body: %s", err) - } - fmt.Fprint(&src, body) - } - - if matches[1] != "" { - src.WriteString(",\n") - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[1], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Reindex", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- Bulk() --------------------------------------------------------- - Pattern: `^POST /?(\S+)?/?_bulk`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^POST /?(?P\S+)?/?_bulk(?P\??[\S/]+)?\s?\n?(?P.+)?`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Bulk(\n") - - if matches[3] != "" { - fmt.Fprintf(&src, "\tstrings.NewReader(`\n%s`),\n", matches[3]) - } - - if matches[1] != "" { - fmt.Fprintf(&src, "\tes.Bulk.WithIndex(%q),\n", matches[1]) - } - - if matches[2] != "" { - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[2], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Bulk", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprint(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- Tasks.Get() ------------------------------------------------------------ - Pattern: `^GET /?_tasks/.+`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^GET /?_tasks/?(?P\S+)?/?(?P\??[\S/]+)?`) - - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Tasks.Get(\n") - - if matches[1] != "" { - fmt.Fprintf(&src, "\t%q,\n", matches[1]) - } - - if matches[2] != "" { - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[2], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - - args, err := paramsToArguments("Tasks.Get", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- Tasks.List() ------------------------------------------------------------ - Pattern: `^GET /?_tasks`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^GET /?_tasks/?(?P\??[\S/]+)?`) - - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Tasks.List(\n") - - if matches[1] != "" { - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[1], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - - args, err := paramsToArguments("Tasks.List", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- Tasks.Cancel() --------------------------------------------------------- - Pattern: `^POST /?_tasks.+_cancel`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^POST /?_tasks/(?P\S+)/_cancel(?P\??[\S/]+)?`) - - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Tasks.Cancel(\n") - if matches[1] != "" { - fmt.Fprintf(&src, "client.Tasks.Cancel.WithTaskID(%q),\n", matches[1]) - } - - if matches[2] != "" { - params, err := url.ParseQuery(strings.TrimPrefix(strings.TrimPrefix(matches[2], "/"), "?")) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - - args, err := paramsToArguments("Tasks.Cancel", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } - - src.WriteString("\t)") - return src.String(), nil - }}, - - { // ----- Indices.Get() ------------------------------------------------- - Pattern: `^GET /?[^/_\s]+`, - Func: func(in string) (string, error) { - var src strings.Builder - - re := regexp.MustCompile(`(?ms)^GET /?(?P[^/\s]+)(?P\??[\S/]+)?$`) - matches := re.FindStringSubmatch(in) - if matches == nil { - return "", errors.New("cannot match example source to pattern") - } - - src.WriteString("\tres, err := client.Indices.Get(") - - if matches[2] != "" { - fmt.Fprintf(&src, "\n\t[]string{%q},\n", matches[1]) - - params, err := queryToParams(matches[2]) - if err != nil { - return "", fmt.Errorf("error parsing URL params: %s", err) - } - args, err := paramsToArguments("Indices.Get", params) - if err != nil { - return "", fmt.Errorf("error converting params to arguments: %s", err) - } - fmt.Fprintf(&src, args) - } else { - fmt.Fprintf(&src, "[]string{%q}", matches[1]) - } - - src.WriteString(")") - return src.String(), nil - }}, -} - -// Translator represents converter from Console source code to Go source code. -// -type Translator struct { - Example Example -} - -// TranslateRule represents a rule for translating code from Console to Go. -// -type TranslateRule struct { - Pattern string - Func func(string) (string, error) -} - -// IsTranslated returns true when a rule for translating the Console example to Go source code exists. -// -func (t Translator) IsTranslated() bool { - var translated bool - - cmds, err := t.Example.Commands() - if err != nil { - panic(fmt.Sprintf("error getting example commands: %s", err)) - } - - for _, c := range cmds { - for _, r := range ConsoleToGo { - if r.Match(c) { - translated = true - } - } - } - - return translated -} - -// Translate returns the Console code translated to Go. -// -func (t Translator) Translate() (string, error) { - var out strings.Builder - - cmds, err := t.Example.Commands() - if err != nil { - return "", fmt.Errorf("error getting example commands: %s", err) - } - - out.WriteRune('\n') - fmt.Fprintf(&out, "\t// tag:%s[]\n", t.Example.Digest) - for i, c := range cmds { - var translated bool - for _, r := range ConsoleToGo { - if translated { - break - } - - if r.Match(c) { - src, err := r.Func(c) - if err != nil { - return "", fmt.Errorf("error translating the example: %s", err) - } - translated = true - - if len(cmds) > 1 { - out.WriteString("\t{\n") - } - out.WriteString(src) - out.WriteRune('\n') - out.WriteString("\tfmt.Println(res, err)\n") - out.WriteString(testCheck) - if len(cmds) > 1 { - out.WriteString("\t}\n") - if i != len(cmds)-1 { - out.WriteString("\n") - } - } - } - } - if !translated { - return "", errors.New("no rule to translate the example") - } - } - fmt.Fprintf(&out, "\t// end:%s[]\n", t.Example.Digest) - return out.String(), nil -} - -// Match returns true when the input matches the rule pattern. -// -func (r TranslateRule) Match(input string) bool { - matched, _ := regexp.MatchString(r.Pattern, input) - return matched -} - -// queryToParams extracts the URL params. -// -func queryToParams(input string) (url.Values, error) { - input = strings.TrimPrefix(input, "/") - input = strings.TrimPrefix(input, "?") - return url.ParseQuery(input) -} - -// paramsToArguments converts params to API arguments. -// -func paramsToArguments(api string, params url.Values) (string, error) { - var b strings.Builder - - keys := make([]string, 0, len(params)) - for k := range params { - keys = append(keys, k) - } - - sort.Strings(keys) - for _, k := range keys { - var ( - name string - value string - ) - - value = strings.Join(params[k], ",") - - switch k { - case "q": - name = "Query" - default: - name = utils.NameToGo(k) - } - - switch k { - case "timeout", "scroll": // duration - if params[k][0] == "" { - break - } - dur, err := time.ParseDuration(params[k][0]) - if err != nil { - return "", fmt.Errorf("error parsing duration [%s]: %s", params[k][0], err) - } - value = fmt.Sprintf("time.Duration(%d)", time.Duration(dur)) - case "from", "size", "terminate_after", "version", "requests_per_second", "scroll_size", "max_num_segments": // numeric - value = fmt.Sprintf("%s", value) - case "pretty", "error_trace": - value = "" // Helper methods don't take any value - case "refresh": - switch api { - case "Index": - if params[k][0] == "" { - value = `"true"` // WithRefresh() needs a string - } else { - value = strconv.Quote(value) - } - case "Reindex", "DeleteByQuery", "UpdateByQuery": - if params[k][0] == "" { - value = "true" // WithRefresh() needs a boolean - } - default: - value = strconv.Quote(value) - } - case "detailed", "flat_settings": // bool - value = string(value) - case "v": // Blank bool - value = "true" - default: - value = strconv.Quote(value) - } - fmt.Fprintf(&b, "\tclient.%s.With%s(%s),\n", api, name, value) - } - - return b.String(), nil -} - -// bodyStringToReader re formats input JSON string and returns it wrapped in strings.NewReader. -// -func bodyStringToReader(input string) (string, error) { - var body bytes.Buffer - err := json.Indent(&body, []byte(input), "\t\t", " ") - if err != nil { - fmt.Printf("Input: %q", input) - return "", err - } - return fmt.Sprintf("strings.NewReader(`%s`)", strings.TrimRight(body.String(), "\n")), nil -} diff --git a/internal/build/cmd/generate/commands/gensource/command.go b/internal/build/cmd/generate/commands/gensource/command.go deleted file mode 100644 index 670150b28..000000000 --- a/internal/build/cmd/generate/commands/gensource/command.go +++ /dev/null @@ -1,304 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gensource - -import ( - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "strings" - "time" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd" - - "github.com/spf13/cobra" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) - -var ( - input *string - output *string - gofmt *bool - color *bool - debug *bool - info *bool -) - -var ( - GitCommit string - GitTag string - EsVersion string -) - -func init() { - input = gensourceCmd.Flags().StringP("input", "i", "", "Path to a folder or files with Elasticsearch REST API specification") - output = gensourceCmd.Flags().StringP("output", "o", "", "Path to a folder for generated output") - gofmt = gensourceCmd.Flags().BoolP("gofmt", "f", true, "Format generated output with 'gofmt'") - color = gensourceCmd.Flags().BoolP("color", "c", true, "Syntax highlight the debug output") - debug = gensourceCmd.Flags().BoolP("debug", "d", false, "Print the generated source to terminal") - info = gensourceCmd.Flags().Bool("info", false, "Print the API details to terminal") - - gensourceCmd.MarkFlagRequired("input") - gensourceCmd.MarkFlagRequired("output") - gensourceCmd.Flags().SortFlags = false - - cmd.RegisterCmd(gensourceCmd) -} - -var gensourceCmd = &cobra.Command{ - Use: "apisource", - Short: "Generate the Go APIs from the Elasticsearch REST API specification", - Run: func(cmd *cobra.Command, args []string) { - command := &Command{ - Input: *input, - Output: *output, - Gofmt: *gofmt, - DebugInfo: *info, - DebugSource: *debug, - ColorizeSource: *color, - } - err := command.Execute() - if err != nil { - utils.PrintErr(err) - os.Exit(1) - } - }, -} - -// Command represents the "gensource" command. -// -type Command struct { - Input string - Output string - Gofmt bool - DebugInfo bool - DebugSource bool - ColorizeSource bool -} - -// Execute runs the command. -// -func (cmd *Command) Execute() (err error) { - var inputFiles []string - - if strings.Contains(cmd.Input, ",") { - inputFiles = strings.Split(cmd.Input, ",") - } else { - inputFiles, err = filepath.Glob(cmd.Input) - if err != nil { - return fmt.Errorf("Failed to glob input %q: %s", cmd.Input, err) - } - } - - if len(inputFiles) < 1 { - return fmt.Errorf("No files matching input %q", cmd.Input) - } - - EsVersion, err = utils.EsVersion(filepath.Dir(inputFiles[0])) - if err != nil { - return err - } - GitCommit, err = utils.GitCommit(filepath.Dir(inputFiles[0])) - if err != nil { - return err - } - GitTag, err = utils.GitTag(filepath.Dir(inputFiles[0])) - if err != nil { - return err - } - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintf(os.Stderr, "Specification: %s", EsVersion) - fmt.Fprintf(os.Stderr, " (%s", GitCommit) - if GitTag != "" { - fmt.Fprintf(os.Stderr, ", %s", GitTag) - } - fmt.Fprintf(os.Stderr, ")\n") - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - - var endpoints []*Endpoint - - stats := struct { - n int - start time.Time - }{start: time.Now()} - - for _, fpath := range inputFiles { - fname := filepath.Base(fpath) - if fname == "_common.json" { - continue - } - - f, err := os.Open(fpath) - if err != nil { - return err - } - - if err := cmd.processFile(f); err != nil { - return fmt.Errorf("Processing file %q: %s", fname, err) - } - - f.Seek(0, 0) - e, err := NewEndpoint(f) - if err != nil { - return fmt.Errorf("error creating endpoint for %q: %s", fname, err) - } - f.Close() - - endpoints = append(endpoints, e) - stats.n++ - } - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintf(os.Stderr, "Processed %d files in %s\n", stats.n, time.Since(stats.start).Truncate(time.Millisecond)) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - - return nil -} - -func (cmd *Command) processFile(f *os.File) (err error) { - var out io.Reader - - fname := filepath.Base(f.Name()) - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintf(os.Stderr, "Processing file %q\n", fname) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - - endpoint, err := NewEndpoint(f) - if err != nil { - return fmt.Errorf("error creating endpoint for %q: %s", fname, err) - } - - gen := Generator{Endpoint: endpoint} - - if cmd.Gofmt { - out, err = gen.OutputFormatted() - } else { - out, err = gen.Output() - } - if err != nil { - if cmd.DebugSource { - utils.PrintSourceWithErr(out, err) - } - return fmt.Errorf("error generating output for %q: %s", fname, err) - } - - if cmd.DebugInfo { - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintf(os.Stderr, gen.Endpoint.DebugInfo()) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - } - - if cmd.DebugSource { - var src io.Reader - var buf bytes.Buffer - tee := io.TeeReader(out, &buf) - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - if cmd.ColorizeSource { - src, err = utils.Chromatize(tee) - if err != nil { - return fmt.Errorf("error syntax highligting the output: %s", err) - } - - _, err = io.Copy(os.Stderr, src) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - } - - _, err = io.Copy(os.Stderr, out) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - - fmt.Fprintf(os.Stderr, "\n\n") - - out = &buf - } - - if cmd.Output == "-" { - _, err = io.Copy(os.Stdout, out) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - } else { - if err := os.MkdirAll(cmd.Output, 0775); err != nil { - return fmt.Errorf("error creating directory: %s", err) - } - - var fName string - if gen.Endpoint.Type == "core" { - fName = filepath.Join(cmd.Output, "api."+gen.Endpoint.Name+".go") - } else { - fName = filepath.Join(cmd.Output, "api."+gen.Endpoint.Type+"."+gen.Endpoint.Name+".go") - } - - f, err := os.OpenFile(fName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) - if err != nil { - return fmt.Errorf("error creating file: %s", err) - } - _, err = io.Copy(f, out) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - if err := f.Close(); err != nil { - return fmt.Errorf("error closing file: %s", err) - } - } - - return nil -} diff --git a/internal/build/cmd/generate/commands/gensource/debug.go b/internal/build/cmd/generate/commands/gensource/debug.go deleted file mode 100644 index c1606f13f..000000000 --- a/internal/build/cmd/generate/commands/gensource/debug.go +++ /dev/null @@ -1,117 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gensource - -import ( - "fmt" - "math" - "strings" - "text/tabwriter" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) - -// DebugInfo returns information about the endpoint as a string. -// -func (e *Endpoint) DebugInfo() string { - var out strings.Builder - w := tabwriter.NewWriter(&out, 0, 0, 1, ' ', 0) - - fmt.Fprintln(&out, strings.Repeat("─", utils.TerminalWidth())) - fmt.Fprintf(&out, "API: %s (%s:%s)\n", e.MethodWithNamespace(), e.Type, e.Name) - fmt.Fprintf(&out, "%s\n", e.Documentation.Description[0:int(math.Min(float64(80), float64(len(e.Documentation.Description))))]) - fmt.Fprintln(&out, strings.Repeat("─", utils.TerminalWidth())) - - fmt.Fprintln(&out, "Paths:") - for _, path := range e.URL.Paths { - fmt.Fprintf(w, "%6s\t%s", path.Methods[0], path.Path) - if path.Deprecated.Version != "" { - fmt.Fprintf(w, "\t*deprecated*") - } - fmt.Fprintf(w, "\n") - } - w.Flush() - - longestPath := e.URL.Paths[0] - for _, v := range e.URL.Paths { - if len(v.Path) > len(longestPath.Path) { - longestPath = v - } - } - - if len(longestPath.Parts) > 0 { - fmt.Fprintln(&out, "Parts:") - for _, part := range longestPath.Parts { - fmt.Fprintf(w, " • %s\t", part.Name) - fmt.Fprintf(w, " %s", part.Type) - if part.Required { - fmt.Fprint(w, ", required") - } - if part.Default != nil { - fmt.Fprintf(w, ", default: %s", part.Default) - } - fmt.Fprint(w, "\n") - } - w.Flush() - } - - if len(e.URL.Params) > 0 { - fmt.Fprintln(&out, "Params:") - for _, param := range e.URL.Params { - fmt.Fprintf(w, " • %s\t %s", param.Name, param.Type) - if param.Required { - fmt.Fprint(w, ", required") - } - if param.Type == "enum" { - fmt.Fprintf(w, ": %s", strings.Join(param.Options, ", ")) - } - if param.Default != nil { - fmt.Fprintf(w, ", default: %s", param.Default) - } - fmt.Fprint(w, "\n") - } - w.Flush() - } - - if e.Body != nil { - fmt.Fprintln(&out, "Body:") - if e.Body.Description != "" { - fmt.Fprintf(&out, " %s.", e.Body.Description) - } - if e.Body.Required { - fmt.Fprintf(&out, " *Required*") - } else { - fmt.Fprintf(&out, " Optional") - } - if e.Body.ContentType != "" { - fmt.Fprintf(&out, ", format: %s", e.Body.ContentType) - } - fmt.Fprintf(&out, "\n") - } - - return out.String() -} diff --git a/internal/build/cmd/generate/commands/gensource/descriptions.go b/internal/build/cmd/generate/commands/gensource/descriptions.go deleted file mode 100644 index d57b0558f..000000000 --- a/internal/build/cmd/generate/commands/gensource/descriptions.go +++ /dev/null @@ -1,534 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gensource - -var apiDescriptionsYAML = ` ---- -bulk: - description: |- - Allows to perform multiple index/update/delete operations in a single request. - -cat.aliases: - description: |- - Shows information about currently configured aliases to indices including filter and routing infos. - -cat.allocation: - description: |- - Provides a snapshot of how many shards are allocated to each data node and how much disk space they are using. - -cat.count: - description: |- - Provides quick access to the document count of the entire cluster, or individual indices. - -cat.fielddata: - description: |- - Shows how much heap memory is currently being used by fielddata on every data node in the cluster. - -cat.health: - description: |- - Returns a concise representation of the cluster health. - -cat.help: - description: - Returns help for the Cat APIs. - -cat.indices: - description: |- - Returns information about indices: number of primaries and replicas, document counts, disk size, ... - -cat.master: - description: |- - Returns information about the master node. - -cat.nodeattrs: - description: |- - Returns information about custom node attributes. - -cat.nodes: - description: |- - Returns basic statistics about performance of cluster nodes. - -cat.pending_tasks: - description: |- - Returns a concise representation of the cluster pending tasks. - -cat.plugins: - description: |- - Returns information about installed plugins across nodes node. - -cat.recovery: - description: |- - Returns information about index shard recoveries, both on-going completed. - -cat.repositories: - description: |- - Returns information about snapshot repositories registered in the cluster. - -cat.segments: - description: |- - Provides low-level information about the segments in the shards of an index. - -cat.shards: - description: |- - Provides a detailed view of shard allocation on nodes. - -cat.snapshots: - description: |- - Returns all snapshots in a specific repository. - -cat.tasks: - description: |- - Returns information about the tasks currently executing on one or more nodes in the cluster. - -cat.templates: - description: |- - Returns information about existing templates. - -cat.thread_pool: - description: |- - Returns cluster-wide thread pool statistics per node. - By default the active, queue and rejected statistics are returned for all thread pools. - -clear_scroll: - description: |- - Explicitly clears the search context for a scroll. - -cluster.allocation_explain: - description: |- - Provides explanations for shard allocations in the cluster. - -cluster.get_settings: - description: |- - Returns cluster settings. - -cluster.health: - description: |- - Returns basic information about the health of the cluster. - -cluster.pending_tasks: - description: |- - Returns a list of any cluster-level changes (e.g. create index, update mapping, - allocate or fail shard) which have not yet been executed. - -cluster.put_settings: - description: |- - Updates the cluster settings. - -cluster.remote_info: - description: |- - Returns the information about configured remote clusters. - -cluster.reroute: - description: |- - Allows to manually change the allocation of individual shards in the cluster. - -cluster.state: - description: |- - Returns a comprehensive information about the state of the cluster. - -cluster.stats: - description: |- - Returns high-level overview of cluster statistics. - -count: - description: |- - Returns number of documents matching a query. - -create: - description: |- - Creates a new document in the index. - - Returns a 409 response when a document with a same ID already exists in the index. - -delete: - description: |- - Removes a document from the index. - -delete_by_query: - description: |- - Deletes documents matching the provided query. - -delete_by_query_rethrottle: - description: |- - Changes the number of requests per second for a particular Delete By Query operation. - -delete_script: - description: |- - Deletes a script. - -exists: - description: |- - Returns information about whether a document exists in an index. - -exists_source: - description: |- - Returns information about whether a document source exists in an index. - -explain: - description: |- - Returns information about why a specific matches (or doesn't match) a query. - -field_caps: - description: |- - Returns the information about the capabilities of fields among multiple indices. - -get: - description: |- - Returns a document. - -get_script: - description: |- - Returns a script. - -get_source: - description: |- - Returns the source of a document. - -index: - description: |- - Creates or updates a document in an index. - -indices.analyze: - description: |- - Performs the analysis process on a text and return the tokens breakdown of the text. - -indices.clear_cache: - description: |- - Clears all or specific caches for one or more indices. - -indices.clone: - description: |- - Clones an existing index into a new index. - -indices.close: - description: |- - Closes an index. - -indices.create: - description: |- - Creates an index with optional settings and mappings. - -indices.delete: - description: |- - Deletes an index. - -indices.delete_alias: - description: |- - Deletes an alias. - -indices.delete_template: - description: |- - Deletes an index template. - -indices.exists: - description: |- - Returns information about whether a particular index exists. - -indices.exists_alias: - description: |- - Returns information about whether a particular alias exists. - -indices.exists_template: - description: |- - Returns information about whether a particular index template exists. - -indices.flush: - description: |- - Performs the flush operation on one or more indices. - -indices.forcemerge: - description: |- - Performs the force merge operation on one or more indices. - -indices.get: - description: |- - Returns information about one or more indices. - -indices.get_alias: - description: |- - Returns an alias. - -indices.get_field_mapping: - description: |- - Returns mapping for one or more fields. - -indices.get_mapping: - description: |- - Returns mappings for one or more indices. - -indices.get_settings: - description: |- - Returns settings for one or more indices. - -indices.get_template: - description: |- - Returns an index template. - -indices.get_upgrade: - description: |- - The _upgrade API is no longer useful and will be removed. - -indices.open: - description: |- - Opens an index. - -indices.put_alias: - description: |- - Creates or updates an alias. - -indices.put_mapping: - description: |- - Updates the index mappings. - -indices.put_settings: - description: |- - Updates the index settings. - -indices.put_template: - description: |- - Creates or updates an index template. - -indices.recovery: - description: |- - Returns information about ongoing index shard recoveries. - -indices.refresh: - description: |- - Performs the refresh operation in one or more indices. - -indices.rollover: - description: |- - Updates an alias to point to a new index when the existing index - is considered to be too large or too old. - -indices.segments: - description: |- - Provides low-level information about segments in a Lucene index. - -indices.shard_stores: - description: |- - Provides store information for shard copies of indices. - -indices.shrink: - description: |- - Allow to shrink an existing index into a new index with fewer primary shards. - -indices.split: - description: |- - Allows you to split an existing index into a new index with more primary shards. - -indices.stats: - description: |- - Provides statistics on operations happening in an index. - -indices.update_aliases: - description: |- - Updates index aliases. - -indices.upgrade: - description: |- - The _upgrade API is no longer useful and will be removed. - -indices.validate_query: - description: |- - Allows a user to validate a potentially expensive query without executing it. - -info: - description: |- - Returns basic information about the cluster. - -ingest.delete_pipeline: - description: |- - Deletes a pipeline. - -ingest.get_pipeline: - description: |- - Returns a pipeline. - -ingest.processor_grok: - description: |- - Returns a list of the built-in patterns. - -ingest.put_pipeline: - description: |- - Creates or updates a pipeline. - -ingest.simulate: - description: |- - Allows to simulate a pipeline with example documents. - -mget: - description: |- - Allows to get multiple documents in one request. - -msearch: - description: |- - Allows to execute several search operations in one request. - -msearch_template: - description: |- - Allows to execute several search template operations in one request. - -mtermvectors: - description: |- - Returns multiple termvectors in one request. - -nodes.hot_threads: - description: |- - Returns information about hot threads on each node in the cluster. - -nodes.info: - description: |- - Returns information about nodes in the cluster. - -nodes.reload_secure_settings: - description: |- - Reloads secure settings. - -nodes.stats: - description: |- - Returns statistical information about nodes in the cluster. - -nodes.usage: - description: |- - Returns low-level information about REST actions usage on nodes. - -ping: - description: - Returns whether the cluster is running. - -put_script: - description: |- - Creates or updates a script. - -rank_eval: - description: |- - Allows to evaluate the quality of ranked search results over a set of typical search queries - -reindex: - description: |- - Allows to copy documents from one index to another, optionally filtering the source - documents by a query, changing the destination index settings, or fetching the - documents from a remote cluster. - -reindex_rethrottle: - description: |- - Changes the number of requests per second for a particular Reindex operation. - -render_search_template: - description: |- - Allows to use the Mustache language to pre-render a search definition. - -scripts_painless_execute: - description: |- - Allows an arbitrary script to be executed and a result to be returned - -scripts_painless_context: - description: |- - Allows to query context information. - -scroll: - description: |- - Allows to retrieve a large numbers of results from a single search request. - -search: - description: |- - Returns results matching a query. - -search_shards: - description: |- - Returns information about the indices and shards that a search request would be executed against. - -search_template: - description: |- - Allows to use the Mustache language to pre-render a search definition. - -snapshot.create: - description: |- - Creates a snapshot in a repository. - -snapshot.create_repository: - description: |- - Creates a repository. - -snapshot.delete: - description: |- - Deletes a snapshot. - -snapshot.delete_repository: - description: |- - Deletes a repository. - -snapshot.get: - description: |- - Returns information about a snapshot. - -snapshot.get_repository: - description: |- - Returns information about a repository. - -snapshot.restore: - description: |- - Restores a snapshot. - -snapshot.status: - description: |- - Returns information about the status of a snapshot. - -snapshot.verify_repository: - description: |- - Verifies a repository. - -tasks.cancel: - description: |- - Cancels a task, if it can be cancelled through an API. - -tasks.get: - description: |- - Returns information about a task. - -tasks.list: - description: |- - Returns a list of tasks. - -termvectors: - description: |- - Returns information and statistics about terms in the fields of a particular document. - -update: - description: |- - Updates a document with a script or partial document. - -update_by_query: - description: |- - Performs an update on every document in the index without changing the source, - for example to pick up a mapping change. - -update_by_query_rethrottle: - description: |- - Changes the number of requests per second for a particular Update By Query operation. -` diff --git a/internal/build/cmd/generate/commands/gensource/generator.go b/internal/build/cmd/generate/commands/gensource/generator.go deleted file mode 100644 index 69472c1db..000000000 --- a/internal/build/cmd/generate/commands/gensource/generator.go +++ /dev/null @@ -1,821 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gensource - -import ( - "bytes" - "fmt" - "io" - "reflect" - "strings" - - "golang.org/x/tools/imports" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) - -// Generator represents the "gensource" generator. -// -type Generator struct { - b bytes.Buffer - - Endpoint *Endpoint -} - -// Output returns the generator output. -// -func (g *Generator) Output() (io.Reader, error) { - g.genHeader() - g.genConstructor() - g.genMethodDefinition() - g.genRequestStruct() - g.w("\n") - g.genDoMethod() - g.genWithOptions() - - return bytes.NewReader(g.b.Bytes()), nil -} - -// OutputFormatted returns a formatted generator output. -// -func (g *Generator) OutputFormatted() (io.Reader, error) { - out, err := g.Output() - if err != nil { - return bytes.NewReader(g.b.Bytes()), err - } - - var b bytes.Buffer - if _, err := io.Copy(&b, out); err != nil { - return bytes.NewReader(g.b.Bytes()), err - } - - fout, err := imports.Process( - "opensearchapi/api."+g.Endpoint.Name+".go", - g.b.Bytes(), - &imports.Options{ - AllErrors: true, - Comments: true, - FormatOnly: false, - TabIndent: true, - TabWidth: 1, - }) - if err != nil { - return bytes.NewReader(b.Bytes()), err - } - - g.b.Reset() - g.b.Write(fout) - - return bytes.NewReader(fout), nil -} - -func (g *Generator) w(s string) { - g.b.WriteString(s) -} - -func (g *Generator) genHeader() { - g.w(`// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details.` + "\n") - g.w("//\n// Code generated") - if EsVersion != "" { - g.w(fmt.Sprintf(" from specification version %s", EsVersion)) - } - g.w(": DO NOT EDIT\n") - g.w("\n") - g.w("package opensearchapi\n") -} - -func (g *Generator) genConstructor() { - g.w(` -func new` + g.Endpoint.MethodWithNamespace() + `Func(t Transport) ` + g.Endpoint.MethodWithNamespace() + ` { - return func(`) - g.genMethodArguments() - g.w(`o ...func(*` + g.Endpoint.MethodWithNamespace() + `Request)) (*Response, error) {`) - if len(g.Endpoint.RequiredArguments()) > 0 { - g.w("\n\t\t" + `var r = ` + g.Endpoint.MethodWithNamespace() + `Request{`) - for i, arg := range g.Endpoint.RequiredArguments() { - if arg.Name == "type" { - continue // Skip the type parameter, "_doc" is used by default - } - g.w(arg.GoName() + ": " + arg.Name) - if i != len(g.Endpoint.RequiredArguments())-1 { - g.w(", ") - } - } - g.w("}\n") - } else { - g.w("\n\t\t" + `var r = ` + g.Endpoint.MethodWithNamespace() + `Request{}` + "\n") - } - g.w(` for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} -`) -} - -func (g *Generator) genMethodDefinition() { - g.w("\n// ----- API Definition -------------------------------------------------------\n\n") - - if g.Endpoint.Documentation.Description != "" { - words := strings.Split(g.Endpoint.Documentation.Description, " ") - initial := strings.ToLower(words[0:1][0]) - description := initial + " " + strings.Join(words[1:], " ") - lines := strings.Split(description, "\n") - - g.w(`// ` + g.Endpoint.MethodWithNamespace() + " " + lines[0:1][0]) - for _, line := range lines[1:] { - g.w("\n// " + line) - } - } - - if g.Endpoint.Stability != "stable" { - g.w("\n//\n// This API is " + g.Endpoint.Stability + ".") - } - - if g.Endpoint.Documentation.URL != "" { - g.w("\n//\n" + `// See full documentation at ` + g.Endpoint.Documentation.URL + ".") - } - - g.w(` -// -type ` + g.Endpoint.MethodWithNamespace() + ` func(`) - g.genMethodArguments() - g.w(`o ...func(*` + g.Endpoint.MethodWithNamespace() + `Request)) (*Response, error) -`) -} - -func (g *Generator) genMethodArguments() { - if len(g.Endpoint.RequiredArguments()) > 0 { - for _, arg := range g.Endpoint.RequiredArguments() { - if arg.Name == "type" { - continue // Skip the type parameter, "_doc" is used by default - } - var argType string - if arg.Name == "body" { - argType = "io.Reader" - } else { - argType = arg.GoType() - } - var argName string - if arg.Name == "type" { - argName = "typ" - } else { - argName = arg.Name - } - g.w(argName + " " + argType) - g.w(", ") - } - } -} - -func (g *Generator) genRequestStruct() { - g.w(` -// ` + g.Endpoint.MethodWithNamespace() + `Request configures the ` + g.Endpoint.HumanMethodWithNamespace() + ` API request. -// -type ` + g.Endpoint.MethodWithNamespace() + `Request struct {`) - specialFields := []string{"index", "type", "id"} - for _, n := range specialFields { - if param, ok := g.Endpoint.URL.AllParts[n]; ok { - g.w("\n\t" + param.GoName()) - g.w("\t" + param.GoType(true)) - } - } - - if len(g.Endpoint.URL.AllParts) > 0 { - g.w("\n") - } - - if g.Endpoint.Body != nil { - g.w("\n\tBody io.Reader") - } - - if len(g.Endpoint.URL.AllParts) > 0 || g.Endpoint.Body != nil { - g.w("\n") - } - - for _, name := range g.Endpoint.URL.PartNamesSorted { - p, ok := g.Endpoint.URL.AllParts[name] - if !ok { - panic(fmt.Sprintf("Part %q not found", name)) - } - - skip := false - for _, v := range specialFields { - if p.Name == v { - skip = true - } - } - if skip { - continue - } - g.w("\n\t" + p.GoName()) - g.w("\t" + p.GoType(true)) - - } - - if len(g.Endpoint.URL.AllParts) > 0 { - g.w("\n") - } - - for _, name := range g.Endpoint.URL.ParamNamesSorted { - p, ok := g.Endpoint.URL.Params[name] - if !ok { - panic(fmt.Sprintf("Parameter %q not found", name)) - } - - if _, ok := g.Endpoint.URL.AllParts[name]; ok { - continue // skip params which are also parts - } - - g.w("\n\t" + p.GoName()) - g.w("\t" + p.GoType(true)) - } - - g.w("\n\n\tPretty\tbool") - g.w("\n\tHuman\tbool") - g.w("\n\tErrorTrace\tbool") - g.w("\n\tFilterPath\t[]string\n") - - g.w("\n\n\tHeader\thttp.Header\n") - - g.w("\n\tctx context.Context\n}\n") -} - -func (g *Generator) genWithOptions() { - // Generate WithContext first - g.w(` -// WithContext sets the request context. -// -func (f ` + g.Endpoint.MethodWithNamespace() + `) WithContext(v context.Context) func(*` + g.Endpoint.MethodWithNamespace() + `Request) { - return func(r *` + g.Endpoint.MethodWithNamespace() + `Request) { - r.ctx = v - } -} -`) - - // Skip adding With... options for arguments which are part of the method signature - skipRequiredArgs := make(map[string]bool) - for _, p := range g.Endpoint.RequiredArguments() { - skipRequiredArgs[p.Name] = true - } - - var methodBody = func(e *Endpoint, a interface{}) string { - var b strings.Builder - - switch a.(type) { - case *Part, *Param: // pass - default: - panic(fmt.Sprintf("FAIL: %q: Unexpected type [%[1]T] for argument: %#[1]v", g.Endpoint.Name, a)) - } - - var ( - methodWithNamespace = e.MethodWithNamespace() - - typ = reflect.TypeOf(a).String() - pFieldName = reflect.ValueOf(a).MethodByName("GoName").Call([]reflect.Value{})[0].String() - pGoType = reflect.ValueOf(a).MethodByName("GoType").Call([]reflect.Value{reflect.ValueOf(false)})[0].String() - // pType = reflect.Indirect(reflect.ValueOf(a)).FieldByName("Type").String() - // pName = reflect.Indirect(reflect.ValueOf(a)).FieldByName("Name").String() - // pGoName = reflect.ValueOf(a).MethodByName("GoName").Call([]reflect.Value{})[0].String() - - pDesc = utils.IDToUpper(strings.ToLower(reflect.Indirect(reflect.ValueOf(a)).FieldByName("Description").String())) - ) - - // Adjust descriptions - if strings.Contains(pDesc, "a comma-separated list") { - pDesc = strings.Replace(pDesc, "a comma-separated list", "a list", -1) - } - if strings.Contains(pDesc, "use `_all` or empty string") { - pDesc = strings.Replace(pDesc, "use `_all` or empty string", "use _all", -1) - } - - // Generate annotation - b.WriteString("\n// With" + pFieldName) - if typ == "*gensource.Part" { - b.WriteString(` - ` + pDesc) - } else { - b.WriteString(` - ` + pDesc) - } - b.WriteString(`.`) - - // Generate function - b.WriteString("\n//\nfunc (f " + methodWithNamespace + `) With` + pFieldName + `(`) - - switch pGoType { - case "bool": - // empty function argument - case "*bool": - b.WriteString(`v bool`) - case "*int": - b.WriteString(`v int`) - case "[]string": - b.WriteString(`v ...string`) - default: - b.WriteString(`v ` + pGoType) - } - - b.WriteString(`) func(*` + methodWithNamespace + `Request) { - return func(r *` + methodWithNamespace + `Request) {` + "\n") - - switch pGoType { - case "bool": - b.WriteString("\t\t" + `r.` + pFieldName + ` = true`) - case "*bool", "*int": - b.WriteString("\t\t" + `r.` + pFieldName + ` = &v`) - default: - b.WriteString("\t\t" + `r.` + pFieldName + ` = v`) - } - - b.WriteString("\n\t}\n}\n") - - return b.String() - } - - // Generate WithBody method - if b := g.Endpoint.Body; b != nil { - // Do not add the option when body is part of the method signature - if !skipRequiredArgs["body"] { - g.w(` -// WithBody` + ` - ` + b.Description + `. -// -func (f ` + g.Endpoint.MethodWithNamespace() + `) WithBody(v io.Reader) func(*` + g.Endpoint.MethodWithNamespace() + `Request) { - return func(r *` + g.Endpoint.MethodWithNamespace() + `Request) { - r.Body = v - } -} -`) - } - } - - // Generate With... methods for parts - for _, pName := range g.Endpoint.URL.PartNamesSorted { - if p, ok := g.Endpoint.URL.AllParts[pName]; ok { - if skipRequiredArgs[p.Name] && p.Name != "type" { - continue - } - - g.w(methodBody(g.Endpoint, p)) - } else { - g.w(`// TODO: ` + p.Name) - } - } - - // Generate With... methods for params - for _, pName := range g.Endpoint.URL.ParamNamesSorted { - if _, ok := g.Endpoint.URL.AllParts[pName]; ok { - continue // skip params which are also parts - } - if p, ok := g.Endpoint.URL.Params[pName]; ok { - g.w(methodBody(g.Endpoint, p)) - } else { - g.w(`// TODO: ` + p.Name) - } - } - - // Generate methods for common parameters - if g.Endpoint.Name != "info" { - g.w(` -// WithPretty makes the response body pretty-printed. -// -func (f ` + g.Endpoint.MethodWithNamespace() + `) WithPretty() func(*` + g.Endpoint.MethodWithNamespace() + `Request) { - return func(r *` + g.Endpoint.MethodWithNamespace() + `Request) { - r.Pretty = true - } -} -`) - } - - g.w(` -// WithHuman makes statistical values human-readable. -// -func (f ` + g.Endpoint.MethodWithNamespace() + `) WithHuman() func(*` + g.Endpoint.MethodWithNamespace() + `Request) { - return func(r *` + g.Endpoint.MethodWithNamespace() + `Request) { - r.Human = true - } -} -`) - - g.w(` -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ` + g.Endpoint.MethodWithNamespace() + `) WithErrorTrace() func(*` + g.Endpoint.MethodWithNamespace() + `Request) { - return func(r *` + g.Endpoint.MethodWithNamespace() + `Request) { - r.ErrorTrace = true - } -} -`) - - g.w(` -// WithFilterPath filters the properties of the response body. -// -func (f ` + g.Endpoint.MethodWithNamespace() + `) WithFilterPath(v ...string) func(*` + g.Endpoint.MethodWithNamespace() + `Request) { - return func(r *` + g.Endpoint.MethodWithNamespace() + `Request) { - r.FilterPath = v - } -} -`) - - // Generate methods for HTTP headers - g.w(` -// WithHeader adds the headers to the HTTP request. -// -func (f ` + g.Endpoint.MethodWithNamespace() + `) WithHeader(h map[string]string) func(*` + g.Endpoint.MethodWithNamespace() + `Request) { - return func(r *` + g.Endpoint.MethodWithNamespace() + `Request) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} -`) - - // Generate methods for the X-Opaque-ID header - g.w(` -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ` + g.Endpoint.MethodWithNamespace() + `) WithOpaqueID(s string) func(*` + g.Endpoint.MethodWithNamespace() + `Request) { - return func(r *` + g.Endpoint.MethodWithNamespace() + `Request) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} -`) -} - -func (g *Generator) genDoMethod() { - g.w(`// Do executes the request and returns response or error. -// -func (r ` + g.Endpoint.MethodWithNamespace() + `Request) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - )` + "\n\n") - - switch g.Endpoint.Name { - case "index": - g.w("\t") - g.w(`if r.DocumentID != "" { - method = "PUT" - } else { - method = "POST" - }`) - g.w("\n\n") - default: - var httpMethod string - // If endpoint has both GET and POST available - // Prefer POST usage in order to prevent go routine leak - // See https://github.com/golang/go/issues/29246 - if g.Endpoint.URL.ContainsMethods("GET", "POST") { - httpMethod = "POST" - } else { - httpMethod = g.Endpoint.URL.Paths[0].Methods[0] - } - g.w("\t" + `method = "` + httpMethod + `"` + "\n\n") - } - - // Get default part values for specific APIs - // TODO: Move to overrides - var defparts bool - switch g.Endpoint.Name { - case "index", "create", "delete", "explain", "exists", "get", "get_source", "update", "termvectors": - for _, p := range g.Endpoint.URL.AllParts { - if p.Default != nil { - var fieldName string - var fieldValue string - var fieldCondition string - - fieldName = p.GoName() - switch p.Type { - case "string", "enum": - fieldCondition = `r.` + fieldName + ` == ""` - fieldValue = `"` + p.Default.(string) + `"` - case "number": - fieldCondition = `r.` + fieldName + ` == 0` - fieldValue = p.Default.(string) - case "list": - fieldCondition = ` len(r.` + fieldName + `) < 1` - fieldValue = `[]string{"` + p.Default.(string) + `"}` - default: - panic(fmt.Sprintf("FAIL: %q: unexpected parameter type %q for URL part %q", g.Endpoint.Name, p.Type, p.Name)) - } - g.w("\t") - g.w(`if ` + fieldCondition + ` { - r.` + fieldName + ` = ` + fieldValue + ` - }` + "\n") - defparts = true - } - } - } - if defparts { - g.w("\n") - } - - // Generate the URL path - // - if f := g.GetOverride("url", g.Endpoint.Name); f != nil { - g.w(f(g.Endpoint)) - } else { - var ( - pathGrow strings.Builder - pathContent strings.Builder - ) - - pathGrow.WriteString(` path.Grow(`) - - // FIXME: Select longest path based on number of template entries, not string length - longestPath := g.Endpoint.URL.Paths[0] - for _, v := range g.Endpoint.URL.Paths { - if len(v.Path) > len(longestPath.Path) { - longestPath = v - } - } - - if len(longestPath.Parts) < 1 { - if len(g.Endpoint.URL.Paths) < 1 { - panic(fmt.Sprintf("FAIL: %q: empty endpoint\n", g.Endpoint.Name)) - } - pathGrow.WriteString(`len("` + longestPath.Path + `")`) - pathContent.WriteString(` path.WriteString("` + longestPath.Path + `")` + "\n") - - } else { - pathParts := make([]string, 0) - apiArgs := g.Endpoint.RequiredArguments() - for _, v := range strings.Split(longestPath.Path, "/") { - if v != "" { - pathParts = append(pathParts, v) - } - } - - r := strings.NewReplacer("{", "", "}", "") - - for _, v := range pathParts { - var p string - - // Required arguments - for _, a := range apiArgs { - if strings.HasPrefix(v, "{") && a.Name == r.Replace(v) { - p = a.GoName() - pathGrow.WriteString(`1 + `) - pathContent.WriteString(` path.WriteString("/")` + "\n") - switch a.Type { - case "string": - pathGrow.WriteString(`len(r.` + p + `) + `) - pathContent.WriteString(` path.WriteString(r.` + p + `)` + "\n") - case "list": - pathGrow.WriteString(`len(strings.Join(r.` + p + `, ",")) + `) - pathContent.WriteString(` path.WriteString(strings.Join(r.` + p + `, ","))` + "\n") - default: - panic(fmt.Sprintf("FAIL: %q: unexpected type %q for URL part %q\n", g.Endpoint.Name, a.Type, a.Name)) - } - break - } - } - - // Optional arguments - if p == "" { - for _, a := range longestPath.Parts { - // fmt.Printf("a: %+v\n", a) - if strings.HasPrefix(v, "{") && a.Name == r.Replace(v) { - p = a.GoName() - - switch a.Type { - case "string": - pathGrow.WriteString(`1 + len(r.` + p + `) + `) - pathContent.WriteString(` if r.` + p + ` != "" {` + "\n") - pathContent.WriteString(` path.WriteString("/")` + "\n") - pathContent.WriteString(` path.WriteString(r.` + p + `)` + "\n") - pathContent.WriteString(` }` + "\n") - case "list": - pathGrow.WriteString(`1 + len(strings.Join(r.` + p + `, ",")) + `) - pathContent.WriteString(` if len(r.` + p + `) > 0 {` + "\n") - pathContent.WriteString(` path.WriteString("/")` + "\n") - pathContent.WriteString(` path.WriteString(strings.Join(r.` + p + `, ","))` + "\n") - pathContent.WriteString(` }` + "\n") - case "int", "long": - pathContent.WriteString(` if r.` + p + ` != nil {` + "\n") - pathContent.WriteString(` value := strconv.FormatInt(int64(*r.` + p + `), 10)` + "\n") - pathContent.WriteString(` path.Grow(1 + len(value))` + "\n") - pathContent.WriteString(` path.WriteString("/")` + "\n") - pathContent.WriteString(` path.WriteString(value)` + "\n") - pathContent.WriteString(` }` + "\n") - default: - panic(fmt.Sprintf("FAIL: %q: unexpected type %q for URL part %q\n", g.Endpoint.Name, a.Type, a.Name)) - } - - break - } - } - } - - // Optional arguments - if p == "" { - for _, a := range g.Endpoint.URL.Params { - if strings.HasPrefix(v, "{") && a.Name == r.Replace(v) { - p = a.GoName() - pathGrow.WriteString("1 +") - pathContent.WriteString(` path.WriteString("/")` + "\n") - switch a.Type { - case "string": - pathGrow.WriteString(`len(r.` + p + `)`) - pathContent.WriteString(` path.WriteString(r.` + p + `)` + "\n") - case "list": - pathGrow.WriteString(`len(strings.Join(r.` + p + `, ","))`) - pathContent.WriteString(` path.WriteString(strings.Join(r.` + p + `, ","))` + "\n") - default: - panic(fmt.Sprintf("FAIL: %q: unexpected type %q for URL param %q\n", g.Endpoint.Name, a.Type, a.Name)) - } - break - } - } - } - - // Static parts - if p == "" { - pathGrow.WriteString(`1 + len("` + v + `") + `) - pathContent.WriteString(` path.WriteString("/")` + "\n") - pathContent.WriteString(` path.WriteString("` + v + `")` + "\n") - } - } - } - - // Write out the content - pathGrow.WriteString(`)`) - g.w(strings.Replace(pathGrow.String(), " + )", ")", 1) + "\n") - g.w(pathContent.String() + "\n") - } - - // Generate the URL params - g.w(` - params = make(map[string]string)` + "\n") - for _, n := range g.Endpoint.URL.ParamNamesSorted { - if p, ok := g.Endpoint.URL.Params[n]; ok { - var ( - fieldName string - fieldType string - fieldValue string - fieldCondition string - ) - - fieldName = p.GoName() - fieldType = p.GoType() - switch fieldType { - case "bool": - fieldCondition = `r.` + fieldName - fieldValue = `strconv.FormatBool(r.` + fieldName + `)` - case "*bool": - fieldCondition = `r.` + fieldName + ` != nil` - fieldValue = `strconv.FormatBool(*r.` + fieldName + `)` - case "string": - fieldCondition = `r.` + fieldName + ` != ""` - fieldValue = `r.` + fieldName - case "int": - fieldCondition = `r.` + fieldName + ` != 0` - fieldValue = `strconv.FormatInt(int64(r.` + fieldName + `), 10)` - case "*int": - fieldCondition = `r.` + fieldName + ` != nil` - fieldValue = `strconv.FormatInt(int64(*r.` + fieldName + `), 10)` - case "uint": - fieldCondition = `r.` + fieldName + ` != 0` - fieldValue = `strconv.FormatUint(uint64(r.` + fieldName + `), 10)` - case "*uint": - fieldCondition = `r.` + fieldName + ` != 0` - fieldValue = `strconv.FormatUint(uint64(*r.` + fieldName + `), 10)` - case "[]string": - fieldCondition = ` len(r.` + fieldName + `) > 0` - fieldValue = `strings.Join(r.` + fieldName + `, ",")` - case "time.Duration": - fieldCondition = `r.` + fieldName + ` != 0` - fieldValue = `formatDuration(r.` + fieldName + `)` - default: // interface{} - fieldCondition = `r.` + fieldName + ` != nil` - // TODO: Use type switching instead? - fieldValue = `fmt.Sprintf("%v", r.` + fieldName + `)` - } - - g.w(` - if ` + fieldCondition + ` { - params["` + p.Name + `"] = ` + fieldValue + ` - }` + "\n") - - } else { - panic(fmt.Sprintf("FAIL: %q: Unknown parameter %q in URL parameters", g.Endpoint.Name, n)) - } - } - - // Common parameters - g.w(` - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - `) - g.w("\n\n") - - // Generate the HTTP request options - var httpBody string - if g.Endpoint.Body != nil { - httpBody = "r.Body" - } else { - httpBody = "nil" - } - - g.w(`req, err := newRequest(method, path.String(), ` + httpBody + `)` + "\n") - g.w(`if err != nil { - return nil, err - }` + "\n\n") - - g.w(`if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - }` + "\n\n") - - if g.Endpoint.Body != nil { - g.w(`if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - }` + "\n\n") - } - - g.w(`if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - }` + "\n\n") - - g.w(`if ctx != nil { - req = req.WithContext(ctx) - }` + "\n\n") - - g.w(` - res, err := transport.Perform(req) - if err != nil { - return nil, err - }` + "\n\n") - - // Generate the return value - g.w(` - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - }` + "\n") - g.w("\n\treturn &response, nil\n") - - g.w("}\n") -} diff --git a/internal/build/cmd/generate/commands/gensource/model.go b/internal/build/cmd/generate/commands/gensource/model.go deleted file mode 100644 index af72cd7f1..000000000 --- a/internal/build/cmd/generate/commands/gensource/model.go +++ /dev/null @@ -1,489 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gensource - -import ( - "encoding/json" - "fmt" - "io" - "sort" - "strings" - "unicode" - - "gopkg.in/yaml.v2" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) - -var ( - apiDescriptions map[interface{}]interface{} -) - -func init() { - err := yaml.NewDecoder(strings.NewReader(apiDescriptionsYAML)).Decode(&apiDescriptions) - if err != nil { - panic(fmt.Sprintf("ERROR: %v", err)) - } -} - -// NewEndpoint creates a new API endpoint. -// -func NewEndpoint(f io.Reader) (*Endpoint, error) { - var endpoint Endpoint - var spec map[string]Endpoint - - if err := json.NewDecoder(f).Decode(&spec); err != nil { - return nil, err - } - - for name, e := range spec { - endpoint = e - endpoint.Name = name - endpoint.URL.Params = endpoint.Params - } - - if endpoint.Type == "" { - endpoint.Type = "core" - } - - endpoint.URL.AllParts = make(map[string]*Part) - - for _, path := range endpoint.URL.Paths { - for partName, part := range path.Parts { - part.Endpoint = &endpoint - part.Name = partName - } - } - - var params [][]string - for _, path := range endpoint.URL.Paths { - var parts []string - for partName := range path.Parts { - parts = append(parts, partName) - } - params = append(params, parts) - } - - var paramsCounter = make(map[string]int) - for _, pp := range params { - for _, p := range pp { - paramsCounter[p] += 1 - } - } - - // Update the required field of path parts - for _, path := range endpoint.URL.Paths { - for partName, part := range path.Parts { - if p, ok := paramsCounter[partName]; ok { - if p == len(params) { - part.Required = true - } - } - } - } - - for paramName, p := range endpoint.URL.Params { - p.Endpoint = &endpoint - p.Name = paramName - } - - // Update the AllParts field - var partSeen = make(map[string]bool) - for _, path := range endpoint.URL.Paths { - for partName, part := range path.Parts { - if !partSeen[partName] { - endpoint.URL.AllParts[partName] = part - } - partSeen[partName] = true - } - } - - if endpoint.Documentation.Description == "" && endpoint.Documentation.URL != "" { - endpoint.Documentation.Description = endpoint.Documentation.URL - } - endpoint.Documentation.URL = "" - - var partNames []string - for param := range paramsCounter { - partNames = append(partNames, param) - } - sort.Slice(partNames, func(i, j int) bool { - return strings.Replace(partNames[i], "_", "", 1) < strings.Replace(partNames[j], "_", "", 1) - }) - endpoint.URL.PartNamesSorted = partNames - - var paramNames []string - for _, param := range endpoint.URL.Params { - paramNames = append(paramNames, param.Name) - } - sort.Slice(paramNames, func(i, j int) bool { - return strings.Replace(paramNames[i], "_", "", 1) < strings.Replace(paramNames[j], "_", "", 1) - }) - endpoint.URL.ParamNamesSorted = paramNames - - for _, path := range endpoint.URL.Paths { - for _, part := range path.Parts { - if part.Name == "type" { - part.Default = "_doc" - } - } - } - - // if info, ok := apiDescriptions[endpoint.Name]; ok { - // if desc, ok := info.(map[interface{}]interface{})["description"].(string); ok { - // endpoint.Documentation.Description = desc - // } - // } - - return &endpoint, nil -} - -// Endpoint represents an API endpoint. -// -type Endpoint struct { - Name string `json:"-"` - Type string `json:"-"` - - Documentation struct { - URL string `json:"url"` - Description string `json:"description"` - } `json:"documentation"` - - Stability string `json:"stability"` - - URL *URL `json:"url"` - Params map[string]*Param `json:"params"` - Body *Body `json:"body"` -} - -// URL represents API endpoint URL. -// -type URL struct { - Endpoint *Endpoint `json:"-"` - - Paths []Path `json:"paths"` - DeprecatedPaths []struct { - Path string `json:"path"` - Version string `json:"version"` - Description string `json:"description"` - } `json:"deprecated_paths"` - Params map[string]*Param `json:"params"` - - AllParts map[string]*Part - PartNamesSorted []string - ParamNamesSorted []string -} - -// Path represents URL path -type Path struct { - Path string `json:"path"` - Methods []string `json:"methods"` - Parts map[string]*Part `json:"parts"` - Deprecated struct { - Version string `json:"version"` - Description string `json:"description"` - } -} - -// Part represents part of the API endpoint URL. -// -type Part struct { - Endpoint *Endpoint `json:"-"` - - Name string `json:"-"` - Default interface{} `json:"-"` - - Type string `json:"type"` - Description string `json:"description"` - Required bool `json:"required"` -} - -// Param represents API endpoint parameter. -// -type Param struct { - Endpoint *Endpoint `json:"-"` - - Name string `json:"-"` - - Type string `json:"type"` - Description string `json:"description"` - Options []string `json:"options"` - Default interface{} `json:"default"` - Required bool `json:"required"` -} - -// Body represents API endpoint body. -// -type Body struct { - Endpoint *Endpoint `json:"-"` - - Description string `json:"description"` - Required bool `json:"required"` - ContentType string `json:"serialize"` -} - -// MethodArgument represents a method argument for API endpoint. -// -type MethodArgument struct { - Endpoint *Endpoint - - Name string - Type string - Description string - Options []string - Default interface{} - Required bool -} - -// Namespace returns the API endpoint namespace. -// -func (e *Endpoint) Namespace() string { - ep := strings.Split(e.Name, ".") - return utils.NameToGo(ep[0]) -} - -// MethodName returns the API endpoint method name. -// -func (e *Endpoint) MethodName() string { - ep := strings.Split(e.Name, ".") - ep = append(ep[:0], ep[1:]...) - ns := make([]string, len(ep)) - for _, v := range ep { - m := strings.Split(v, "_") - mn := make([]string, len(m)) - for _, vv := range m { - mn = append(mn, strings.Title(vv)) - } - ns = append(ns, strings.Join(mn, "")) - } - return strings.Join(ns, "") -} - -// MethodWithNamespace returns the API endpoint method name with namespace. -// -func (e *Endpoint) MethodWithNamespace() string { - return utils.APIToGo(e.Name) -} - -// HumanMethodWithNamespace returns the API endpoint method name in humanized form. -// -func (e *Endpoint) HumanMethodWithNamespace() string { - var ( - src = e.MethodWithNamespace() - out string - ) - for i, l := range src { - if unicode.IsUpper(l) && i > 0 { - if i+2 <= len(src) && unicode.IsUpper([]rune(src[i+1 : i+2])[0]) { - out += string(l) - } else { - out += " " + string(l) - } - } else { - out += string(l) - } - } - return out -} - -// RequiredArguments return the list of required method arguments. -// -func (e *Endpoint) RequiredArguments() []MethodArgument { - var args = make([]MethodArgument, 0) - var prominentArgs = []string{ - "index", - "type", - "id", - "repository", - "snapshot", - "snapshot_id", - "calendar_id", - "job_id", - "username", - "name", - } - - var contains = func(s string) bool { - for _, v := range args { - if v.Name == s { - return true - } - } - return false - } - - // Return the prominent arguments first - for _, d := range prominentArgs { - for _, p := range e.URL.Paths[0].Parts { - if p.Name != d { - continue - } - if p.Required { - args = append(args, MethodArgument{ - Endpoint: e, - Name: p.Name, - Type: p.Type, - Description: p.Description, - Required: true, - }) - } - // Make the 'type' required for selected APIs - if p.Name == "type" && (e.Name == "index" || e.Name == "create") { - args = append(args, MethodArgument{ - Endpoint: e, - Name: p.Name, - Type: p.Type, - Description: p.Description, - Required: true, - }) - } - } - } - - // Return the body after prominent arguments - if e.Body != nil && e.Body.Required { - args = append(args, MethodArgument{ - Endpoint: e, - Name: "body", - Description: e.Body.Description, - }) - } - - // Return rest of the URL parts - for _, p := range e.URL.Paths[0].Parts { - if contains(p.Name) { - continue - } - if p.Required { - args = append(args, MethodArgument{ - Endpoint: e, - Name: p.Name, - Type: p.Type, - Description: p.Description, - Required: true, - }) - } - } - - // Return URL params - for _, p := range e.URL.Params { - if contains(p.Name) { - continue - } - if p.Required { - args = append(args, MethodArgument{ - Endpoint: e, - Name: p.Name, - Type: p.Type, - Description: p.Description, - Options: p.Options, - Default: p.Default, - Required: p.Required, - }) - } - } - - return args -} - -// GoName returns a Go name for part. -// -func (p *Part) GoName() string { - switch { - case p.Name == "context": - return "ScriptContext" - default: - return utils.NameToGo(p.Name, p.Endpoint.MethodWithNamespace()) - } -} - -// GoType returns a Go type for part. -// -func (p *Part) GoType(comment ...bool) string { - return utils.TypeToGo(p.Type) -} - -// GoName returns a Go name for parameter. -// -func (p *Param) GoName() string { - switch { - case p.Name == "context": - return "ScriptContext" - case p.Name == "q": - return "Query" - default: - return utils.NameToGo(p.Name, p.Endpoint.MethodWithNamespace()) - } -} - -// GoType returns a Go type for parameter. -// -func (p *Param) GoType(comment ...bool) string { - if f := (&Generator{Endpoint: p.Endpoint}).GetOverride("polymorphic-param", p.Endpoint.Name); f != nil { - if out := f(p.Endpoint, p.Name); out != "" { - return out - } - } - return utils.TypeToGo(p.Type) -} - -// GoName returns a Go name for method argument. -// -func (p *MethodArgument) GoName() string { - return utils.NameToGo(p.Name, p.Endpoint.MethodWithNamespace()) -} - -// GoType returns a Go type for method argument. -// -func (p *MethodArgument) GoType(comment ...bool) string { - return utils.TypeToGo(p.Type) -} - -// ContainsMethods return true if every method passed in argument is present in every Path -func (u *URL) ContainsMethods(methods ...string) bool { - for _, path := range u.Paths { - // Fast exit if both collections are not the same size - if len(methods) != len(path.Methods) { - return false - } - - // We iterate over every items - items := make(map[string]struct{}) - for _, v := range path.Methods { - items[v] = struct{}{} - } - - for _, method := range methods { - if _, ok := items[method]; ok { - continue - } - return false - } - continue - } - return true -} diff --git a/internal/build/cmd/generate/commands/gensource/overrides.go b/internal/build/cmd/generate/commands/gensource/overrides.go deleted file mode 100644 index d566a7ca0..000000000 --- a/internal/build/cmd/generate/commands/gensource/overrides.go +++ /dev/null @@ -1,131 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gensource - -var ( - overrideRules map[string][]OverrideRule -) - -// OverrideFunc defines a function to override generated code for endpoint. -// -type OverrideFunc func(*Endpoint, ...interface{}) string - -// OverrideRule represents an override rule. -// -type OverrideRule struct { - Func OverrideFunc - Matching []string -} - -// GetOverride returns an override function for id and API name. -// -func (g *Generator) GetOverride(id, apiName string) OverrideFunc { - if rr, ok := overrideRules[id]; ok { - for _, r := range rr { - if r.Match(apiName) { - return r.Func - } - } - } - return nil -} - -// Match returns true when API name matches a rule. -// -func (r OverrideRule) Match(apiName string) bool { - for _, v := range r.Matching { - if v == "*" { - return true - } - if v == apiName { - return true - } - } - return false -} - -func init() { - overrideRules = map[string][]OverrideRule{ - - "polymorphic-param": {{ - Matching: []string{"search"}, - Func: func(e *Endpoint, i ...interface{}) string { - if len(i) > 0 { - switch i[0] { - case "track_total_hits": - return "interface{}" - } - } - return "" - }, - }}, - - "url": { - { - Matching: []string{"cluster.stats"}, - Func: func(*Endpoint, ...interface{}) string { - return ` - path.Grow(len("/nodes/_cluster/stats/nodes/") + len(strings.Join(r.NodeID, ","))) - path.WriteString("/") - path.WriteString("_cluster") - path.WriteString("/") - path.WriteString("stats") - if len(r.NodeID) > 0 { - path.WriteString("/") - path.WriteString("nodes") - path.WriteString("/") - path.WriteString(strings.Join(r.NodeID, ",")) - } -` - }, - }, - { - Matching: []string{"indices.put_mapping"}, - Func: func(*Endpoint, ...interface{}) string { - return ` - path.Grow(len(strings.Join(r.Index, ",")) + len("/_mapping") + 1) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_mapping") -` - }, - }, - { - Matching: []string{"scroll"}, - Func: func(*Endpoint, ...interface{}) string { - return ` - path.Grow(len("/_search/scroll")) - path.WriteString("/_search/scroll") -` - }, - }, - }, - } -} diff --git a/internal/build/cmd/generate/commands/gensource/testdata/info.json b/internal/build/cmd/generate/commands/gensource/testdata/info.json deleted file mode 100644 index 07ecbec29..000000000 --- a/internal/build/cmd/generate/commands/gensource/testdata/info.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "info": { - "stability": "stable", - "documentation": { - "url": "https://opensearch.org/docs", - "description": "Returns basic information about the cluster." - }, - "url": { - "paths": [ - { - "path": "/", - "methods": ["GET"] - } - ] - }, - "params": {} - } -} \ No newline at end of file diff --git a/internal/build/cmd/generate/commands/genstruct/command.go b/internal/build/cmd/generate/commands/genstruct/command.go deleted file mode 100644 index 0109dbd4f..000000000 --- a/internal/build/cmd/generate/commands/genstruct/command.go +++ /dev/null @@ -1,393 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package genstruct - -import ( - "bytes" - "fmt" - "go/types" - "io" - "os" - "path/filepath" - "strings" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd" - - "golang.org/x/tools/go/packages" - "golang.org/x/tools/imports" - - "github.com/spf13/cobra" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) - -var ( - GitCommit string - GitTag string - EsVersion string -) - -var ( - output *string - gofmt *bool - color *bool - debug *bool - info *bool - - pkgNames []string -) - -func init() { - if pkgNamesEnv := os.Getenv("PACKAGE_NAMES"); pkgNamesEnv != "" { - pkgNames = strings.Split(pkgNamesEnv, ",") - } else { - pkgNames = []string{ - "github.com/opensearch-project/opensearch-go/opensearchapi", - } - } - - output = genapiCmd.Flags().StringP("output", "o", "", "Path to a folder for generated output") - gofmt = genapiCmd.Flags().BoolP("gofmt", "f", true, "Format generated output with 'gofmt'") - color = genapiCmd.Flags().BoolP("color", "c", true, "Syntax highlight the debug output") - debug = genapiCmd.Flags().BoolP("debug", "d", false, "Print the generated source to terminal") - info = genapiCmd.Flags().Bool("info", false, "Print the API details to terminal") - genapiCmd.Flags().SortFlags = false - - cmd.RegisterCmd(genapiCmd) -} - -var genapiCmd = &cobra.Command{ - Use: "apistruct", - Short: "Generate the main Go API struct and constructor", - Run: func(cmd *cobra.Command, args []string) { - command := &Command{ - Output: *output, - Gofmt: *gofmt, - DebugSource: *debug, - ColorizeSource: *color, - } - err := command.Execute() - if err != nil { - utils.PrintErr(err) - os.Exit(1) - } - }, -} - -// Command represents the "genapi" command. -// -type Command struct { - Output string - Gofmt bool - DebugSource bool - ColorizeSource bool -} - -// Execute runs the command. -// -func (cmd *Command) Execute() (err error) { - EsVersion, err = utils.EsVersion("") - if err != nil { - return err - } - GitCommit, err = utils.GitCommit("") - if err != nil { - return err - } - GitTag, err = utils.GitTag("") - if err != nil { - return err - } - return cmd.processAPIConstructor() -} - -func (cmd *Command) processAPIConstructor() (err error) { - var ( - namespaces []string - endpoints []*types.TypeName - - b bytes.Buffer - i int - n int - m int - ) - - namespaces = []string{ - // Core APIs - // - "Cat", - "Cluster", - "Indices", - "Ingest", - "Nodes", - "Remote", - "Snapshot", - "Tasks", - - // XPack APIs - // - "AsyncSearch", - "CCR", - "ILM", - "License", - "Migration", - "ML", - "Monitoring", - "Rollup", - "Security", - "SQL", - "SSL", - "Watcher", - "XPack", - } - - lpkgs, err := packages.Load(&packages.Config{Mode: packages.LoadTypes}, pkgNames...) - if err != nil { - fmt.Printf("Error loading packages: %s\n", err) - return err - } - - for _, lpkg := range lpkgs { - n++ - - if cmd.DebugSource { - fmt.Println(lpkg.Types) - } - - scope := lpkg.Types.Scope() - for _, name := range scope.Names() { - m++ - obj := scope.Lookup(name) - // Skip unexported objects - if !obj.Exported() { - continue - } - - // Skip non-structs - structObj, ok := obj.Type().Underlying().(*types.Struct) - if !ok { - continue - } - - // Skip non-request objects - if !strings.HasSuffix(obj.Name(), "Request") { - continue - } - - // Append API struct to endpoints - endpoints = append(endpoints, obj.(*types.TypeName)) - - i++ - fmt.Printf("%-3d | %s{}\n", i, obj.Name()) - for j := 0; j < structObj.NumFields(); j++ { - field := structObj.Field(j) - if cmd.DebugSource { - fmt.Printf(" %s %s\n", field.Name(), field.Type()) - } - } - } - } - b.WriteString(`// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -//`) - b.WriteString("\n") - b.WriteString("// Code generated") - if EsVersion != "" || GitCommit != "" || GitTag != "" { - b.WriteString(fmt.Sprintf(" from specification version %s", EsVersion)) - if GitCommit != "" { - b.WriteString(fmt.Sprintf(" (%s", GitCommit)) - if GitTag != "" { - b.WriteString(fmt.Sprintf("|%s", GitTag)) - } - b.WriteString(")") - } - } - b.WriteString(": DO NOT EDIT\n") - b.WriteString("\n") - - b.WriteString(`package opensearchapi - -// API contains the Elasticsearch APIs -// -type API struct { -`) - for _, n := range namespaces { - b.WriteString(fmt.Sprintf("\t%[1]s *%[1]s\n", n)) - } - - b.WriteString("\n") - - for _, e := range endpoints { - skip := false - name := strings.ReplaceAll(e.Name(), "Request", "") - - // Skip APIs in namespace - for _, n := range namespaces { - if strings.HasPrefix(strings.ToLower(name), strings.ToLower(n)) { - skip = true - } - } - if !skip { - b.WriteString(fmt.Sprintf("\t%[1]s %[1]s\n", name)) - } - } - - b.WriteString(`}` + "\n\n") - - for _, n := range namespaces { - b.WriteString(`// ` + n + ` contains the ` + n + ` APIs` + "\n") - b.WriteString(`type ` + n + ` struct {` + "\n") - for _, e := range endpoints { - name := strings.ReplaceAll(e.Name(), "Request", "") - if strings.HasPrefix(strings.ToLower(name), strings.ToLower(n)) { - methodName := strings.ReplaceAll(name, n, "") - // Some methods are equal to the namespace (like 'rollup.rollup') - // and we don't want to have an empty string here. - if len(methodName) == 0 { - methodName = strings.Replace(name, n, "", 1) - } - b.WriteString(fmt.Sprintf("\t%s %s\n", methodName, name)) - } - } - b.WriteString("}\n\n") - } - - b.WriteString(`// New creates new API -// -func New(t Transport) *API { - return &API{ -`) - - for _, e := range endpoints { - skip := false - name := strings.ReplaceAll(e.Name(), "Request", "") - - for _, n := range namespaces { - if strings.HasPrefix(strings.ToLower(name), strings.ToLower(n)) { - skip = true - } - } - if !skip { - b.WriteString(fmt.Sprintf("\t\t%[1]s: new%[1]sFunc(t),\n", name)) - } - } - - for _, n := range namespaces { - b.WriteString(fmt.Sprintf("\t\t%[1]s: &%[1]s{\n", n)) - for _, e := range endpoints { - name := strings.ReplaceAll(e.Name(), "Request", "") - if strings.HasPrefix(strings.ToLower(name), strings.ToLower(n)) { - methodName := strings.ReplaceAll(name, n, "") - // Some methods are equal to the namespace (like 'rollup.rollup') - // and we don't want to have an empty string here. - if len(methodName) == 0 { - methodName = strings.Replace(name, n, "", 1) - } - b.WriteString(fmt.Sprintf("\t\t\t%s: new%sFunc(t),\n", methodName, name)) - } - } - b.WriteString("\t\t},\n") - } - - b.WriteString(` } -} -`) - - if cmd.Gofmt { - out, err := imports.Process( - "opensearchapi/api._.go", - b.Bytes(), - &imports.Options{ - AllErrors: true, - Comments: true, - FormatOnly: false, - TabIndent: true, - TabWidth: 1, - }) - if err != nil { - return err - } - b = *bytes.NewBuffer(out) - } - - if cmd.DebugSource { - var src io.Reader - var buf bytes.Buffer - tee := io.TeeReader(bytes.NewReader(b.Bytes()), &buf) - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - if cmd.ColorizeSource { - src, err = utils.Chromatize(tee) - if err != nil { - return fmt.Errorf("error syntax highligting the output: %s", err) - } - } else { - src = bytes.NewReader(b.Bytes()) - } - - _, err = io.Copy(os.Stderr, src) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - - fmt.Fprintf(os.Stderr, "\n\n") - } - - fname := filepath.Join(cmd.Output, "api._.go") - f, err := os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755) - if err != nil { - return fmt.Errorf("error creating file: %s", err) - } - _, err = io.Copy(f, &b) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - if err := f.Close(); err != nil { - return fmt.Errorf("error closing file: %s", err) - } - return nil -} diff --git a/internal/build/cmd/generate/commands/gentests/.gitignore b/internal/build/cmd/generate/commands/gentests/.gitignore deleted file mode 100644 index 904bcd74d..000000000 --- a/internal/build/cmd/generate/commands/gentests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -api_registry.gen.go diff --git a/internal/build/cmd/generate/commands/gentests/command.go b/internal/build/cmd/generate/commands/gentests/command.go deleted file mode 100644 index e90b73091..000000000 --- a/internal/build/cmd/generate/commands/gentests/command.go +++ /dev/null @@ -1,318 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gentests - -//go:generate go run gen_api_registry.go - -import ( - "bytes" - "errors" - "fmt" - "io" - "os" - "path/filepath" - "strings" - "time" - - "github.com/spf13/cobra" - yaml "gopkg.in/yaml.v2" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd" - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) - -var ( - input *string - output *string - gofmt *bool - color *bool - debug *bool - info *bool - - // Populated by 'go generate' - apiRegistry map[string]map[string]string -) - -var ( - GitCommit string - GitTag string - EsVersion string -) - -func init() { - input = gentestsCmd.Flags().StringP("input", "i", "", "Path to a folder or files with Elasticsearch REST API specification") - output = gentestsCmd.Flags().StringP("output", "o", "", "Path to a folder for generated output") - gofmt = gentestsCmd.Flags().BoolP("gofmt", "f", true, "Format generated output with 'gofmt'") - color = gentestsCmd.Flags().BoolP("color", "c", true, "Syntax highlight the debug output") - debug = gentestsCmd.Flags().BoolP("debug", "d", false, "Print the generated source to terminal") - info = gentestsCmd.Flags().Bool("info", false, "Print the API details to terminal") - - gentestsCmd.MarkFlagRequired("input") - gentestsCmd.MarkFlagRequired("output") - - cmd.RegisterCmd(gentestsCmd) -} - -var gentestsCmd = &cobra.Command{ - Use: "apitests", - Short: "Generate the Go integration tests from the Elasticsearch common test suite", - Run: func(cmd *cobra.Command, args []string) { - command := &Command{ - Input: *input, - Output: *output, - Gofmt: *gofmt, - DebugInfo: *info, - DebugSource: *debug, - ColorizeSource: *color, - } - err := command.Execute() - if err != nil { - utils.PrintErr(err) - os.Exit(1) - } - }, -} - -// Command represents the "gentests" command. -// -type Command struct { - Input string - Output string - Gofmt bool - DebugInfo bool - DebugSource bool - ColorizeSource bool -} - -// Execute runs the command. -// -func (cmd *Command) Execute() error { - if len(apiRegistry) < 1 { - return fmt.Errorf("API registry in 'api_registry.gen.go' is empty: Did you run go generate?") - } - - inputFiles, err := filepath.Glob(cmd.Input) - if err != nil { - return fmt.Errorf("Failed to glob input %q: %s", cmd.Input, err) - } - - if len(inputFiles) < 1 { - return fmt.Errorf("No files matching input %q", cmd.Input) - } - - EsVersion, err = utils.EsVersion(filepath.Dir(inputFiles[0])) - if err != nil { - return err - } - if EsVersion == "" { - return errors.New("Elasticsearch version is empty") - } - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2;1m") - } - fmt.Fprintf(os.Stderr, "Elasticsearch %s\n", EsVersion) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - - GitCommit, err = utils.GitCommit(filepath.Dir(inputFiles[0])) - if err != nil { - return fmt.Errorf("Failed to get Git commit: %s", err) - } - GitTag, _ = utils.GitTag(filepath.Dir(inputFiles[0])) - - stats := struct { - n int - start time.Time - }{start: time.Now()} - - for _, fpath := range inputFiles { - var skip bool - - if filepath.Ext(fpath) != ".yml" && filepath.Ext(fpath) != ".yaml" { - skip = true - } - - for _, skipFile := range skipFiles { - if strings.HasSuffix(fpath, skipFile) { - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0;33m") - } - fmt.Fprintf(os.Stderr, "Skipping %q\n", fpath) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - skip = true - } - } - - if skip { - continue - } - - if err := cmd.processFile(fpath); err != nil { - return fmt.Errorf("Processing file %q: %s", fpath, err) - } - stats.n++ - } - - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintf(os.Stderr, "Processed %d files in %s\n", stats.n, time.Since(stats.start).Truncate(time.Millisecond)) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - - return nil -} - -func (cmd *Command) processFile(fpath string) (err error) { - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", utils.TerminalWidth())) - fmt.Fprintf(os.Stderr, "Processing %q\n", fpath) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - - var out io.Reader - var payloads []TestPayload - - f, err := os.Open(fpath) - if err != nil { - return err - } - defer f.Close() - - patched, err := PatchTestSource(fpath, f) - if err != nil { - return fmt.Errorf("cannot patch source: %s", err) - } - - dec := yaml.NewDecoder(patched) - - for { - var payload interface{} - err := dec.Decode(&payload) - if err == io.EOF { - break - } - if err != nil { - return fmt.Errorf("parse error: %s", err) - } - payloads = append(payloads, TestPayload{fpath, payload}) - } - - ts := NewTestSuite(fpath, payloads) - - if cmd.DebugInfo { - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprint(os.Stderr, ts.DebugInfo()) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\n\x1b[0m") - } - } - - if ts.Skip { - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintf(os.Stderr, "Skipping test suite %q", ts.Name()) - if utils.IsTTY() { - fmt.Fprint(os.Stderr, "\n\x1b[0m") - } - return nil - } - - gen := Generator{TestSuite: ts} - - if cmd.Gofmt { - out, err = gen.OutputFormatted() - } else { - out, err = gen.Output() - } - if err != nil { - if cmd.DebugSource { - utils.PrintSourceWithErr(out, err) - } - return fmt.Errorf("error generating output: %s", err) - } - - if cmd.DebugSource { - var src io.Reader - var buf bytes.Buffer - tee := io.TeeReader(out, &buf) - - src, err = utils.Chromatize(tee) - if err != nil { - return fmt.Errorf("error syntax highligting the output: %s", err) - } - - _, err = io.Copy(os.Stderr, src) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - - out = &buf - } - - if cmd.Output == "-" { - _, err = io.Copy(os.Stdout, out) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - } else { - if err := os.MkdirAll(cmd.Output, 0775); err != nil { - return fmt.Errorf("error creating directory: %s", err) - } - - fName := filepath.Join(cmd.Output, gen.TestSuite.Filename()+"_test.go") - f, err := os.OpenFile(fName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755) - if err != nil { - return fmt.Errorf("error creating file: %s", err) - } - _, err = io.Copy(f, out) - if err != nil { - return fmt.Errorf("error copying output: %s", err) - } - if err := f.Close(); err != nil { - return fmt.Errorf("error closing file: %s", err) - } - } - - return nil -} diff --git a/internal/build/cmd/generate/commands/gentests/debug.go b/internal/build/cmd/generate/commands/gentests/debug.go deleted file mode 100644 index d30ca3594..000000000 --- a/internal/build/cmd/generate/commands/gentests/debug.go +++ /dev/null @@ -1,122 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gentests - -import ( - "fmt" - "strings" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) - -// DebugInfo returns information about the endpoint as a string. -// -func (tg TestSuite) DebugInfo() string { - var out strings.Builder - - fmt.Fprintln(&out, strings.Repeat("─", utils.TerminalWidth())) - fmt.Fprint(&out, "["+tg.Name()+"]\n") - fmt.Fprintln(&out, strings.Repeat("─", utils.TerminalWidth())) - - if len(tg.Setup) > 0 { - for _, a := range tg.Setup { - fmt.Fprint(&out, "[setup] ") - fmt.Fprint(&out, a.Method()+"(") - var i int - for k, v := range a.Params() { - i++ - fmt.Fprint(&out, ""+k+": "+fmt.Sprintf("%v", v)) - if i < len(a.Params()) { - fmt.Fprint(&out, ", ") - } - } - fmt.Fprint(&out, ")") - fmt.Fprint(&out, "\n") - } - } - - if len(tg.Teardown) > 0 { - for _, a := range tg.Teardown { - fmt.Fprint(&out, "[tdown] ") - fmt.Fprint(&out, a.Method()+"(") - var i int - for k, v := range a.Params() { - i++ - fmt.Fprint(&out, ""+k+": "+fmt.Sprintf("%v", v)) - if i < len(a.Params()) { - fmt.Fprint(&out, ", ") - } - } - fmt.Fprint(&out, ")\n") - } - } - - for _, t := range tg.Tests { - if utils.IsTTY() { - fmt.Fprint(&out, "\x1b[1;2m") - } - fmt.Fprintln(&out, t.Name+":") - if utils.IsTTY() { - fmt.Fprint(&out, "\x1b[0;2m") - } - for _, a := range t.Setup { - fmt.Fprintf(&out, " [setup] ") - fmt.Fprint(&out, a.Method()+"()\n") - } - for _, a := range t.Teardown { - fmt.Fprintf(&out, " [tdown] ") - fmt.Fprint(&out, a.Method()+"()\n") - } - for _, a := range t.Steps { - switch a.(type) { - case Action: - aa := a.(Action) - fmt.Fprintf(&out, " ==> ") - fmt.Fprint(&out, aa.Method()+"(") - var i int - for k, v := range aa.Params() { - i++ - fmt.Fprint(&out, ""+k+": "+fmt.Sprintf("%v", v)) - if i < len(aa.Params()) { - fmt.Fprint(&out, ", ") - } - } - fmt.Fprint(&out, ")\n") - case Assertion: - aa := a.(Assertion) - fmt.Fprintf(&out, " ~~> ") - fmt.Fprintf(&out, "%q: %s", aa.operation, aa.payload) - fmt.Fprint(&out, "\n") - default: - panic(fmt.Sprintf("Unknown step %T", a)) - } - } - } - - fmt.Fprintln(&out, strings.Repeat("─", utils.TerminalWidth())) - return out.String() -} diff --git a/internal/build/cmd/generate/commands/gentests/gen_api_registry.go b/internal/build/cmd/generate/commands/gentests/gen_api_registry.go deleted file mode 100644 index c8a1ee0f0..000000000 --- a/internal/build/cmd/generate/commands/gentests/gen_api_registry.go +++ /dev/null @@ -1,156 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -// +build ignore - -package main - -import ( - "bytes" - "fmt" - "go/format" - "go/types" - "log" - "os" - "strings" - "time" - - "golang.org/x/tools/go/packages" -) - -var ( - pkgNames []string - debug bool -) - -func init() { - if pkgNamesEnv := os.Getenv("PACKAGE_NAMES"); pkgNamesEnv != "" { - pkgNames = strings.Split(pkgNamesEnv, ",") - } else { - pkgNames = []string{ - "github.com/opensearch-project/opensearch-go/opensearchapi", - } - } - - if _, ok := os.LookupEnv(""); ok { - debug = true - } -} - -func main() { - log.SetFlags(0) - - log.Println("Generating API registry into api_registry.gen.go") - log.Println(strings.Repeat("=", 80)) - - lpkgs, err := packages.Load(&packages.Config{Mode: packages.LoadTypes}, pkgNames...) - if err != nil { - log.Fatalf("Error loading packages: %s", err) - } - - var ( - s = time.Now() - b bytes.Buffer - i int - n int - m int - ) - - b.WriteString("// Code generated by go generate: DO NOT EDIT\n\n") - b.WriteString("package gentests\n\n") - b.WriteString("func init() {\n") - b.WriteString("apiRegistry = map[string]map[string]string{\n\n") - - for _, lpkg := range lpkgs { - n++ - - log.Println(lpkg.Types) - log.Println(strings.Repeat("-", 80)) - - scope := lpkg.Types.Scope() - for _, name := range scope.Names() { - m++ - - obj := scope.Lookup(name) - - // Skip unexported objects - if !obj.Exported() { - continue - } - - // Skip non-structs - structObj, ok := obj.Type().Underlying().(*types.Struct) - if !ok { - continue - } - - // Skip non-request objects - if !strings.HasSuffix(obj.Name(), "Request") { - continue - } - - i++ - log.Printf("%-3d | %s{}\n", i, obj.Name()) - b.WriteString(fmt.Sprintf("%q: map[string]string{\n", obj.Name())) - - for j := 0; j < structObj.NumFields(); j++ { - field := structObj.Field(j) - if debug { - log.Printf(" %s %s", field.Name(), field.Type()) - } - b.WriteString(fmt.Sprintf("%q: %q,\n", field.Name(), field.Type())) - } - if debug { - log.Printf("\n") - } - b.WriteString("},\n\n") - } - } - - b.WriteString("}\n") - b.WriteString("}\n") - - out, err := format.Source(b.Bytes()) - if err != nil { - log.Println(strings.Repeat("~", 80)) - b.WriteTo(os.Stdout) - log.Println(strings.Repeat("~", 80)) - log.Fatalf("Error formatting the source: %s", err) - } - - outFile, err := os.Create("api_registry.gen.go") - if err != nil { - log.Fatalf("Error creating registry file: %s", err) - } - - _, err = outFile.Write(out) - if err != nil { - log.Fatalf("Error writing output to file: %s", err) - } - - log.Println(strings.Repeat("=", 80)) - log.Printf("Processed %d package(s) and %d object(s) in %s.\n", n, m, time.Since(s).Truncate(time.Millisecond)) -} diff --git a/internal/build/cmd/generate/commands/gentests/generator.go b/internal/build/cmd/generate/commands/gentests/generator.go deleted file mode 100644 index 06cc716db..000000000 --- a/internal/build/cmd/generate/commands/gentests/generator.go +++ /dev/null @@ -1,984 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gentests - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "regexp" - "strconv" - "strings" - "time" - - "golang.org/x/tools/imports" -) - -var ( - goruncache map[string]string -) - -func init() { - goruncache = make(map[string]string) -} - -// Generator represents the "gentests" generator. -// -type Generator struct { - b bytes.Buffer - - TestSuite TestSuite -} - -// Output returns the generator output. -// -func (g *Generator) Output() (io.Reader, error) { - name := g.TestSuite.Name() - - g.genFileHeader() - g.w("func Test" + name + "(t *testing.T) {\n") - g.genInitializeClient() - g.genHelpers() - g.genCommonSetup() - - if len(g.TestSuite.Setup) > 0 { - g.w("// ----- Test Suite Setup --------------------------------------------------------\n") - g.w("testSuiteSetup := func() {\n") - g.genSetupTeardown(g.TestSuite.Setup) - g.w("}\n") - g.w("_ = testSuiteSetup\n") - g.w("// --------------------------------------------------------------------------------\n") - g.w("\n") - } - if len(g.TestSuite.Teardown) > 0 { - g.w("\t// Teardown\n") - g.w("\tdefer func(t *testing.T) {\n") - g.genSetupTeardown(g.TestSuite.Teardown) - g.w("\t}(t)\n") - } - for i, t := range g.TestSuite.Tests { - g.w("\n") - g.genLocationYAML(t) - g.w("\t" + `t.Run("` + strings.ReplaceAll(t.Name, " ", "_") + `", ` + "func(t *testing.T) {\n") - if !g.genSkip(t) { - g.w("\tdefer recoverPanic(t)\n") - g.w("\tcommonSetup()\n") - if len(g.TestSuite.Setup) > 0 { - g.w("\ttestSuiteSetup()\n") - } - g.w("\n") - if len(t.Setup) > 0 { - g.w("\t// Test setup\n") - g.genSetupTeardown(t.Setup) - } - if len(t.Teardown) > 0 { - g.w("\t// Test teardown\n") - g.w("\tdefer func(t) {\n") - g.genSetupTeardown(t.Teardown) - g.w("\t}(t *testing.T)\n") - } - if len(t.Setup) > 0 || len(t.Teardown) > 0 { - g.w("\n") - } - g.genSteps(t) - } - g.w("\t})\n") - if i < len(g.TestSuite.Tests)-1 { - g.w("\n") - } - } - g.w("}\n") - return bytes.NewReader(g.b.Bytes()), nil -} - -// OutputFormatted returns a formatted generator output. -// -func (g *Generator) OutputFormatted() (io.Reader, error) { - out, err := g.Output() - if err != nil { - return bytes.NewReader(g.b.Bytes()), err - } - - var b bytes.Buffer - if _, err := io.Copy(&b, out); err != nil { - return bytes.NewReader(g.b.Bytes()), err - } - - fout, err := imports.Process( - "", - g.b.Bytes(), - &imports.Options{ - AllErrors: true, - Comments: true, - FormatOnly: false, - TabIndent: true, - TabWidth: 1, - }) - if err != nil { - return bytes.NewReader(b.Bytes()), err - } - - g.b.Reset() - g.b.Write(fout) - - return bytes.NewReader(fout), nil -} - -func (g *Generator) w(s string) { - g.b.WriteString(s) -} - -func (g *Generator) gorun(code string) (string, error) { - if goruncache[code] != "" { - return goruncache[code], nil - } - - dir, err := ioutil.TempDir("tmp", "gorun") - if err != nil { - return "", fmt.Errorf("gorun: %s", err) - } - f, err := os.Create(filepath.Join(dir, "type_for_struct_field.go")) - if err != nil { - return "", fmt.Errorf("gorun: %s", err) - } - defer func() { - f.Close() - os.RemoveAll(dir) - }() - - // fmt.Println(code) - if err := ioutil.WriteFile(f.Name(), []byte(code), 0644); err != nil { - return "", fmt.Errorf("gorun: %s", err) - } - - cmd := exec.Command("go", "run", f.Name()) - out, err := cmd.Output() - if err != nil { - if e, ok := err.(*exec.ExitError); ok { - return "", fmt.Errorf("gorun: %s", e.Stderr) - } - return "", fmt.Errorf("gorun: %s", err) - } - - goruncache[code] = string(out) - - return string(out), nil -} - -func (g *Generator) genFileHeader() { - g.w("// Code generated") - if EsVersion != "" || GitCommit != "" || GitTag != "" { - g.w(" from YAML test suite version") - if GitCommit != "" { - g.w(fmt.Sprintf(" %s", GitCommit)) - if GitTag != "" { - g.w(fmt.Sprintf("|%s", GitTag)) - } - } - } - g.w(" -- DO NOT EDIT\n") - g.w("\n") - g.w("package opensearchapi_test\n") - g.w(` -import ( - encjson "encoding/json" - encyaml "gopkg.in/yaml.v2" - "fmt" - "context" - "crypto/tls" - "net/url" - "os" - "testing" - "time" - - "github.com/opensearch-project/opensearch-go/v2" - "github.com/opensearch-project/opensearch-go/v2/opensearchapi" - "github.com/opensearch-project/opensearch-go/v2/opensearchtransport" -) - -var ( - // Prevent compilation errors for unused packages - _ = fmt.Printf - _ = encjson.NewDecoder - _ = encyaml.NewDecoder - _ = tls.Certificate{} - _ = url.QueryEscape -)` + "\n") -} - -func (g *Generator) genInitializeClient() { - g.w(` - cfg := opensearch.Config{} - `) - - g.w(` - if os.Getenv("DEBUG") != "" { - cfg.Logger = &opensearchtransport.ColorLogger{ - Output: os.Stdout, - // EnableRequestBody: true, - EnableResponseBody: true, - } - }` + "\n") - - g.w(` - client, eserr := opensearch.NewClient(cfg) - if eserr != nil { - t.Fatalf("Error creating the client: %s\n", eserr) - } - -`) -} - -func (g *Generator) genHelpers() { - g.w(`recoverPanic := func(t *testing.T) { - reLocation := regexp.MustCompile("(.*_test.go:\\d+).*") - if rec := recover(); rec != nil { - var loc string - s := strings.Split(string(debug.Stack()), "\n") - for i := len(s) - 1; i >= 0; i-- { - if reLocation.MatchString(s[i]) { - loc = strings.TrimSpace(s[i]) - break - } - } - t.Fatalf("Panic: %s in %s", rec, reLocation.ReplaceAllString(loc, "$1")) - } -} -_ = recoverPanic -` + "\n") - - g.w(` - handleResponseError := func(t *testing.T, res *opensearchapi.Response) { - if res.IsError() { - reLocation := regexp.MustCompile("(.*_test.go:\\d+).*") - var loc string - s := strings.Split(string(debug.Stack()), "\n") - for i := len(s) - 1; i >= 0; i-- { - if reLocation.MatchString(s[i]) { - loc = strings.TrimSpace(s[i]) - break - } - } - t.Logf("Response error: %s in %s", res, reLocation.ReplaceAllString(loc, "$1")) - } - } - _ = handleResponseError -`) - g.w("\n\n") -} - -// Reference: https://github.com/opensearch-project/OpenSearch/blob/main/test/framework/src/main/java/org/opensearch/test/rest/OpenSearchRestTestCase.java -// -func (g *Generator) genCommonSetup() { - g.w(` - // ----- Common Setup ------------------------------------------------------------- - commonSetup := func() { - var res *opensearchapi.Response - - { - res, _ = client.Cluster.Health(client.Cluster.Health.WithWaitForNoInitializingShards(true)) - if res != nil && res.Body != nil { - defer res.Body.Close() - } - } - - { - res, _ = client.Indices.Delete( - []string{"*"}, - client.Indices.Delete.WithExpandWildcards("all")) - if res != nil && res.Body != nil { - defer res.Body.Close() - } - } - - { - var r map[string]interface{} - res, _ = client.Indices.GetTemplate() - if res != nil && res.Body != nil { - defer res.Body.Close() - json.NewDecoder(res.Body).Decode(&r) - for templateName, _ := range r { - if strings.HasPrefix(templateName, ".") { - continue - } - if templateName == "security_audit_log" { - continue - } - if templateName == "logstash-index-template" { - continue - } - client.Indices.DeleteTemplate(templateName) - } - } - } - - { - res, _ = client.Indices.DeleteIndexTemplate("*") - if res != nil && res.Body != nil { defer res.Body.Close() } - } - - { - res, _ = client.Indices.DeleteAlias([]string{"_all"}, []string{"_all"}) - if res != nil && res.Body != nil { defer res.Body.Close() } - } - - { - var r map[string]interface{} - res, _ = client.Snapshot.GetRepository() - if res != nil && res.Body != nil { - defer res.Body.Close() - json.NewDecoder(res.Body).Decode(&r) - for repositoryID, _ := range r { - var r map[string]interface{} - res, _ = client.Snapshot.Get(repositoryID, []string{"_all"}) - json.NewDecoder(res.Body).Decode(&r) - if r["responses"] != nil { - for _, vv := range r["responses"].([]interface{}) { - for _, v := range vv.(map[string]interface{})["snapshots"].([]interface{}) { - snapshotID, ok := v.(map[string]interface{})["snapshot"] - if !ok { - continue - } - client.Snapshot.Delete(repositoryID, fmt.Sprintf("%s", snapshotID)) - } - } - } - client.Snapshot.DeleteRepository([]string{fmt.Sprintf("%s", repositoryID)}) - } - } - } - - { - res, _ = client.Cluster.Health(client.Cluster.Health.WithWaitForStatus("yellow")) - if res != nil && res.Body != nil { - defer res.Body.Close() - } - } - } - _ = commonSetup - - `) -} - -func (g *Generator) genLocationYAML(t Test) { - f, err := os.Open(t.Filepath) - if err != nil { - g.w(fmt.Sprintf("// Error opening file: %s\n", err)) - } - - scanner := bufio.NewScanner(f) - var i int - for scanner.Scan() { - i++ - tname := scanner.Text() - tname = strings.TrimRight(tname, `:`) - tname = strings.NewReplacer(`\"`, `"`).Replace(tname) - tname = strings.TrimPrefix(tname, `"`) - tname = strings.TrimSuffix(tname, `"`) - - if tname == t.OrigName { - // TODO: Github URL (with proper branch/commit/etc) - g.w("\t// Source: " + t.Filepath + fmt.Sprintf(":%d", i) + "\n\t//\n") - } - } - if err := scanner.Err(); err != nil { - g.w(fmt.Sprintf("// Error reading file: %s\n", err)) - } -} - -func (g *Generator) genSkip(t Test) (skipped bool) { - // Check the custom skip list - if skips, ok := skipTests[t.BaseFilename()]; ok { - if len(skips) < 1 { - g.w("\t// Skipping all tests in '" + t.BaseFilename() + "'\n") - g.w("\tt.SkipNow()\n\n") - return true - } - - for _, skip := range skips { - if skip == t.OrigName { - g.w("\tt.SkipNow()\n\n") - return true - } - } - } - - // Check the skip property coming from YAML - if t.Skip { - if t.SkipInfo != "" { - g.w("\tt.Skip(" + strconv.Quote(t.SkipInfo) + ")\n\n") - return true - } else { - g.w("\tt.SkipNow()\n\n") - return true - } - } - - return false -} - -func (g *Generator) genSetupTeardown(actions []Action) { - g.genVarSection(Test{}) - - for _, a := range actions { - g.genAction(a, false) - g.w("\n") - } -} - -func (g *Generator) genSteps(t Test) { - var skipBody bool - if !t.Steps.ContainsAssertion() && !t.Steps.ContainsCatch() && !t.Steps.ContainsStash() { - skipBody = true - } - g.genVarSection(t, skipBody) - - for _, step := range t.Steps { - switch step.(type) { - case Action: - // Generate debug info - var dbg strings.Builder - dbg.WriteString("\t\t// => " + step.(Action).Method() + "(") - var j int - for k, v := range step.(Action).Params() { - j++ - dbg.WriteString(k + ": " + strings.Replace(fmt.Sprintf("%v", v), "\n", "|", -1)) - if j < len(step.(Action).Params()) { - dbg.WriteString(", ") - } - } - dbg.WriteString(") ") - pad := 101 - dbg.Len() - if pad < 0 { - pad = 0 - } - g.w(dbg.String() + strings.Repeat("-", pad) + "\n\t\t//\n") - - // Generate the action - g.genAction(step.(Action), skipBody) - g.w("\t\t// " + strings.Repeat("-", 96) + "\n\n") - case Assertion: - // Generate debug info - g.w("\t\t// ~> ") - g.w(fmt.Sprintf("%q: ", step.(Assertion).operation)) - g.w(strings.Replace(fmt.Sprintf("%s", step.(Assertion).payload), "\n", "|", -1)) - g.w("\n") - // Generate the assertion - g.genAssertion(step.(Assertion)) - g.w("\n") - case Stash: - // Generate setting the stash - g.genStashSet(step.(Stash)) - g.w("\n") - default: - panic(fmt.Sprintf("Unknown step %T", step)) - } - } -} - -func (g *Generator) genVarSection(t Test, skipBody ...bool) { - g.w("\t\tvar (\n") - g.w("\t\t\treq opensearchapi.Request\n") - g.w("\t\t\tres *opensearchapi.Response\n") - g.w("\t\t\terr error\n\n") - - g.w("\t\t\tstash = make(map[string]interface{}, 0)\n\n") - - if (len(skipBody) < 1 || (len(skipBody) > 0 && skipBody[0] == false)) && - (t.Steps.ContainsAssertion() || t.Steps.ContainsCatch() || true) { - g.w("\t\t\tbody []byte\n") - g.w("\t\t\tmapi map[string]interface{}\n") - g.w("\t\t\tslic []interface{}\n") - } - - if t.Steps.ContainsAssertion("is_false", "is_true") { - g.w("\n\t\t\tvalue reflect.Value\n") - } - - g.w("\n") - g.w("\t\t\tassertion bool\n") - - g.w("\t\t\tactual interface{}\n") - g.w("\t\t\texpected interface{}\n") - g.w("\n") - - if t.Steps.ContainsAssertion("match", "match-regexp") { - g.w("\n\t\t\tre *regexp.Regexp\n") - g.w("\t\t\tmatch bool\n") - } - - g.w("\t\t)\n\n") - - if (len(skipBody) < 1 || (len(skipBody) > 0 && skipBody[0] == false)) && - (t.Steps.ContainsAssertion() || t.Steps.ContainsCatch() || true) { - g.w("\t\t_ = mapi\n") - g.w("\t\t_ = slic\n") - g.w("\n") - g.w(`handleResponseBody := func(t *testing.T, res *opensearchapi.Response) { - // Reset deserialized structures - mapi = make(map[string]interface{}) - slic = make([]interface{}, 0) - - var err error - body, err = ioutil.ReadAll(res.Body) - if err != nil { - t.Fatalf("Error reading body: %s", err) - } - res.Body.Close() - res.Body = ioutil.NopCloser(bytes.NewBuffer(body)) - - if len(body) < 1 { - // FIXME: Hack to prevent EOF errors - return - } - - if len(res.Header) > 0 { - if strings.Contains(res.Header["Content-Type"][0], "text/plain") { - return - } - - if strings.Contains(res.Header["Content-Type"][0], "yaml") { - if strings.HasPrefix(string(body), "---\n-") { - if err := encyaml.NewDecoder(res.Body).Decode(&slic); err != nil { - t.Fatalf("Error parsing the response body: %s", err) - } - } else { - if err := encyaml.NewDecoder(res.Body).Decode(&mapi); err != nil { - t.Fatalf("Error parsing the response body: %s", err) - } - } - return - } - } - - d := encjson.NewDecoder(res.Body) - d.UseNumber() - - if strings.HasPrefix(string(body), "[") { - if err := d.Decode(&slic); err != nil { - t.Fatalf("Error parsing the response body: %s", err) - } - } else { - if err := d.Decode(&mapi); err != nil { - t.Fatalf("Error parsing the response body: %s", err) - } - } - }` + "\n") - } - - g.w("\n") - - g.w("\t\t_ = stash\n") - - if t.Steps.ContainsAssertion("is_false", "is_true") { - g.w("\t\t_ = value\n") - } - - g.w("\t\t_ = assertion\n") - - g.w("\t\t_ = actual\n") - g.w("\t\t_ = expected\n") - - if t.Steps.ContainsAssertion("match", "match-regexp") { - g.w("\n") - g.w("\t\t_ = re\n") - g.w("\t\t_ = match\n") - } - - g.w("\n") -} - -func (g *Generator) genAction(a Action, skipBody ...bool) { - // Initialize the request - g.w("\t\treq = opensearchapi." + a.Request() + "{\n") - - // Pass the parameters - for k, v := range a.Params() { - // fmt.Printf("%s.%s: <%T> %v\n", a.Request(), k, v, v) - - if strings.HasPrefix(fmt.Sprintf("%s", v), "$") { - v = `stash[` + strconv.Quote(strings.ReplaceAll(strings.ReplaceAll(fmt.Sprintf("%s", v), "{", ""), "}", "")) + `]` - } - - switch v.(type) { - case bool: - g.w("\t\t\t" + k + ": ") - - typ, ok := apiRegistry[a.Request()][k] - if !ok { - panic(fmt.Sprintf("%s.%s: field not found", a.Request(), k)) - } - - switch typ { - case "bool": - g.w(strconv.FormatBool(v.(bool))) - case "*bool": - g.w(`opensearchapi.BoolPtr(` + strconv.FormatBool(v.(bool)) + `)`) - case "string": - g.w(`"` + strconv.FormatBool(v.(bool)) + `"`) - case "[]string": - // TODO: Listify - g.w(`[]string{"` + strconv.FormatBool(v.(bool)) + `"}`) - default: - g.w(strconv.FormatBool(v.(bool))) - } - g.w(",\n") - - case string: - if k == "Body" { - g.w("\t\t\t" + k + ": ") - body := v.(string) - if !strings.HasSuffix(body, "\n") { - body = body + "\n" - } - g.w("strings.NewReader(`" + body + "`)") - } else { - g.w("\t\t\t" + k + ": ") - // TODO: Handle comma separated strings as lists - - // fmt.Printf("%s: %#v\n", a.Request(), apiRegistry[a.Request()]) - // fmt.Printf("%s: %#v\n", k, apiRegistry[a.Request()][k]) - typ, ok := apiRegistry[a.Request()][k] - if !ok { - panic(fmt.Sprintf("%s.%s: field not found", a.Request(), k)) - } - - var value string - if strings.HasPrefix(v.(string), "stash[") { - switch typ { - case "bool": - value = `fmt.Sprintf("%v", ` + v.(string) + `)` - case "string": - value = fmt.Sprintf("%s.(string)", v) - case "[]string": - // TODO: Comma-separated list => Quoted list - value = fmt.Sprintf(`[]string{%s.(string)}`, v) - case "int": - value = `func() int { - switch ` + v.(string) + `.(type) { - case int: - return ` + v.(string) + `.(int) - case float64: - return int(` + v.(string) + `.(float64)) - } - case json.Number: - v, _ := ` + v.(string) + `.(encjson.Number).Int64() - vv := int(v) - return vv - panic(fmt.Sprintf(` + "`" + `Unexpected type %T for ` + v.(string) + "`" + `, ` + v.(string) + `)) - }()` - case "*int": - value = `func() *int { - switch ` + v.(string) + `.(type) { - case int: - v := ` + v.(string) + `.(int) - return &v - case float64: - v := int(` + v.(string) + `.(float64)) - return &v - case json.Number: - v, _ := ` + v.(string) + `.(encjson.Number).Int64() - vv := int(v) - return &vv - } - panic(fmt.Sprintf(` + "`" + `Unexpected type %T for ` + v.(string) + "`" + `, ` + v.(string) + `)) - }()` - case "time.Duration": - value = `fmt.Sprintf("%d", ` + v.(string) + `)` - default: - panic(fmt.Sprintf("Unexpected type %q for value %v", typ, v)) - } - } else { - switch typ { - case "[]string": - value = `[]string{` + fmt.Sprintf("%q", v) + `}` - case "time.Duration": - // re := regexp.MustCompile("^(\\d+).*") - // value = re.ReplaceAllString(fmt.Sprintf("%s", v), "$1") - inputValue := v.(string) - if strings.HasSuffix(inputValue, "d") { - inputValue = inputValue[:len(inputValue)-1] - numericValue, err := strconv.Atoi(inputValue) - if err != nil { - panic(fmt.Sprintf("Cannot convert duration [%s]: %s", inputValue, err)) - } - // Convert to hours - inputValue = fmt.Sprintf("%dh", numericValue*24) - } - - dur, err := time.ParseDuration(inputValue) - if err != nil { - panic(fmt.Sprintf("Cannot parse duration [%s]: %s", v, err)) - } - value = fmt.Sprintf("%d", dur.Nanoseconds()) - default: - if strings.HasSuffix(k, "ID") { - value = fmt.Sprintf("url.QueryEscape(%q)", v) - } else { - value = fmt.Sprintf("%q", v) - } - - } - } - g.w(value) - } - g.w(",\n") - - case int, *int, float64: - g.w("\t\t\t" + k + ": ") - - typ, ok := apiRegistry[a.Request()][k] - if !ok { - panic(fmt.Sprintf("%s.%s: field not found", a.Request(), k)) - } - - var value string - switch typ { - case "string": - value = `"` + fmt.Sprintf("%d", v) + `"` - case "[]string": - value = `[]string{"` + fmt.Sprintf("%d", v) + `"}` - case "time.Duration": - re := regexp.MustCompile("^(\\d+).*") - value = re.ReplaceAllString(fmt.Sprintf("%d", v), "$1") - case "*int": - switch v.(type) { - case int: - g.w(`opensearchapi.IntPtr(` + fmt.Sprintf("%d", v) + `)`) - case float64: - if vv, ok := v.(float64); ok { - g.w(`opensearchapi.IntPtr(` + fmt.Sprintf("%d", int(vv)) + `)`) - } - default: - panic(fmt.Sprintf("Unexpected type [%T] for [%s]", v, k)) - } - default: - value = fmt.Sprintf("%v", v) - } - g.w(value) - g.w(",\n") - - case []interface{}: - g.w("\t\t\t" + k + ": ") - - typ, ok := apiRegistry[a.Request()][k] - if !ok { - panic(fmt.Sprintf("%s.%s: field not found", a.Request(), k)) - } - - switch typ { - case "string": - switch v.(type) { - case string: - g.w("`" + v.(string) + "`") - case []interface{}: - vvv := make([]string, 0) - for _, vv := range v.([]interface{}) { - vvv = append(vvv, fmt.Sprintf("%s", vv)) - } - g.w("`" + strings.Join(vvv, ",") + "`") - default: - panic(fmt.Sprintf("<%s> %s{}.%s: unexpected value <%T> %#v", typ, a.Request(), k, v, v)) - } - case "[]string": - qv := make([]string, 0) - for _, vv := range v.([]interface{}) { - // TODO: Check type - qv = append(qv, fmt.Sprintf("%q", vv.(string))) - } - g.w(`[]string{` + strings.Join(qv, ",") + `}`) - case "io.Reader": - // Serialize Bulk payloads ... - if k == "Body" { - var b strings.Builder - for _, vv := range v.([]interface{}) { - switch vv.(type) { - case string: - b.WriteString(vv.(string)) - default: - j, err := json.Marshal(convert(vv)) - if err != nil { - panic(fmt.Sprintf("%s{}.%s: %s (%s)", a.Request(), k, err, v)) - } - b.WriteString(string(j)) - } - b.WriteString("\n") - } - b.WriteString("\n") - g.w("\t\tstrings.NewReader(`" + b.String() + "`)") - // ... or just convert the value to JSON - } else { - j, err := json.Marshal(convert(v)) - if err != nil { - panic(fmt.Sprintf("%s{}.%s: %s (%s)", a.Request(), k, err, v)) - } - g.w("\t\tstrings.NewReader(`" + fmt.Sprintf("%s", j) + "`)") - } - } - g.w(",\n") - - case map[interface{}]interface{}: - g.w("\t\t\t" + k + ": ") - // vv := unstash(convert(v).(map[string]interface{})) - // fmt.Println(vv) - j, err := json.Marshal(convert(v)) - if err != nil { - panic(fmt.Sprintf("JSON parse error: %s; %s", err, v)) - } else { - // Unstash values - reStash := regexp.MustCompile(`("\$[^"]+")`) - j = reStash.ReplaceAll(j, []byte("` + strconv.Quote(fmt.Sprintf(\"%v\", stash[$1])) + `")) - - g.w("\t\tstrings.NewReader(`" + fmt.Sprintf("%s", j) + "`)") - g.w(",\n") - } - - default: - g.w(fmt.Sprintf("\t\t// TODO: %s (%v)\n", k, v)) - } - } - - if len(a.headers) > 0 { - if strings.Contains(a.headers["Accept"], "yaml") && strings.HasPrefix(a.Request(), "Cat") { - g.w("\t\t" + `Format: "yaml",` + "\n") - } - - g.w("\t\tHeader: http.Header{\n") - for name, value := range a.headers { - - if name == "Content-Type" && value == "application/json" { - continue - } - - if name == "Authorization" { - auth_fields := strings.Split(value, " ") - auth_name := auth_fields[0] - auth_value := auth_fields[1] - if strings.HasPrefix(auth_value, "$") { - auth_value = `fmt.Sprintf("%s", stash["` + strings.ReplaceAll(strings.ReplaceAll(auth_value, "{", ""), "}", "") + `"])` - } else { - auth_value = `"` + auth_value + `"` - } - g.w("\t\t\t" + `"Authorization": []string{"` + auth_name + ` " + ` + auth_value + `},` + "\n") - - } else { - g.w("\t\t\t\"" + name + "\": []string{\"" + value + "\"},\n") - } - - } - g.w("\t\t},\n") - } - - g.w("\t\t}\n\n") - - // Get response - g.w("\t\tres, err = req.Do(context.Background(), client)\n") - - g.w(` if err != nil { - t.Fatalf("ERROR: %s", err) - } - defer res.Body.Close() - `) - - g.w("\n\n") - - if len(a.catch) < 1 { - // Handle error responses - g.w(` handleResponseError(t, res)` + "\n") - } else { - // TODO: Test catch - } - - if len(skipBody) < 1 || (len(skipBody) > 0 && skipBody[0] == false) { - // Read and parse the body - g.w(` handleResponseBody(t, res)` + "\n") - } -} - -func (g *Generator) genAssertion(a Assertion) { - g.w(a.Condition()) - g.w(a.Error() + "\n") - g.w("}\n") // Close the condition -} - -func (g *Generator) genStashSet(s Stash) { - g.w(fmt.Sprintf("// Set %q\n", s.Key())) - - value := s.Value() - if strings.HasPrefix(value, `mapi["#`) { - switch { - case strings.HasPrefix(value, `mapi["#base64EncodeCredentials`): - i, j := strings.Index(value, "("), strings.Index(value, ")") - values := strings.Split(value[i+1:j], ",") - value = `base64.StdEncoding.EncodeToString([]byte(` - value += `strings.Join([]string{` - for n, v := range values { - value += `mapi["` + v + `"].(string)` - if n < len(values)-1 { - value += "," - } - } - value += `}, ":")` - value += `))` - default: - panic(fmt.Sprintf("Unknown transformation: %s", value)) - } - } - - g.w(fmt.Sprintf("stash[%q] = %s\n", s.Key(), value)) -} - -func convert(i interface{}) interface{} { - switch x := i.(type) { - case map[interface{}]interface{}: - m2 := map[string]interface{}{} - for k, v := range x { - var ks string - switch k.(type) { - case string: - ks = k.(string) - case int: - ks = fmt.Sprintf("%d", k) - default: - ks = fmt.Sprintf("%v", k) - } - m2[ks] = convert(v) - } - return m2 - case []interface{}: - for i, v := range x { - x[i] = convert(v) - } - } - return i -} diff --git a/internal/build/cmd/generate/commands/gentests/model.go b/internal/build/cmd/generate/commands/gentests/model.go deleted file mode 100644 index 6e480906d..000000000 --- a/internal/build/cmd/generate/commands/gentests/model.go +++ /dev/null @@ -1,924 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gentests - -import ( - "bytes" - "fmt" - "os" - "path/filepath" - "regexp" - "strconv" - "strings" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) - -var reFilename = regexp.MustCompile(`\d*_?(.+)\.ya?ml`) -var reNumber = regexp.MustCompile(`^\d+$`) -var reBaseFilename = regexp.MustCompile(`rest-api-spec/test/\w+/(.*$)`) - -// TestPayload represents a single raw section (`---`) from the YAML file. -// -type TestPayload struct { - Filepath string - Payload interface{} -} - -// TestSuite represents a group of tests (a "section") in one file. -// -type TestSuite struct { - Dir string - Filepath string - Skip bool - SkipInfo string - Type string - - Setup []Action - Teardown []Action - - Tests []Test -} - -// Test represents a single named test. -// -type Test struct { - Name string - Filepath string - OrigName string - - Skip bool - SkipInfo string - - Setup []Action - Teardown []Action - - Steps Steps -} - -// Steps represents the test steps. -type Steps []Step - -// Step represents an Action or an Assertion. -// -type Step interface{} - -// Action represents an API action (`do`). -// -type Action struct { - payload interface{} - - method string - params map[interface{}]interface{} - catch string - headers map[string]string -} - -// Assertion represents a test assertion (`is_true`, `match`, etc). -// -type Assertion struct { - payload interface{} - - operation string -} - -// Stash represents the registry for `set` operations. -// -type Stash struct { - payload interface{} -} - -// NewTestSuite returns a test group from the payloads. -// -func NewTestSuite(fpath string, payloads []TestPayload) TestSuite { - ts := TestSuite{ - Dir: strings.Title(filepath.Base(filepath.Dir(fpath))), - Filepath: fpath, - } - - if ts.Type == "" { - ts.Type = "free" - } - - for _, payload := range payloads { - sec_keys := utils.MapKeys(payload.Payload) - switch { - case len(sec_keys) > 0 && strings.Contains(strings.Join(sec_keys, ","), "setup") || strings.Contains(strings.Join(sec_keys, ","), "teardown"): - for k, v := range payload.Payload.(map[interface{}]interface{}) { - switch k { - case "setup": - for _, vv := range v.([]interface{}) { - for k, vvv := range vv.(map[interface{}]interface{}) { - if k == "do" { - ts.Setup = append(ts.Setup, NewAction(vvv)) - } - } - } - case "teardown": - for _, vv := range v.([]interface{}) { - for k, vvv := range vv.(map[interface{}]interface{}) { - if k == "do" { - ts.Teardown = append(ts.Teardown, NewAction(vvv)) - } - } - } - } - } - default: - for k, v := range payload.Payload.(map[interface{}]interface{}) { - var t Test - var steps []Step - - for _, vv := range v.([]interface{}) { - switch utils.MapKeys(vv)[0] { - case "skip": - var ( - ok bool - skip_v string - skip_r string - ) - - skip := vv.(map[interface{}]interface{})["skip"] - - if skip_v, ok = skip.(map[interface{}]interface{})["version"].(string); ok { - if skip_rr, ok := skip.(map[interface{}]interface{})["reason"].(string); ok { - skip_r = skip_rr - } - if skip_v == "all" { - t.Skip = true - t.SkipInfo = "Skipping all versions" - break - } - if ts.SkipEsVersion(skip_v) { - // fmt.Printf("Skip: %q, EsVersion: %s, Skip: %v, Reason: %s\n", skip_v, EsVersion, ts.SkipEsVersion(skip_v), skip_r) - t.Skip = true - t.SkipInfo = skip_r - } - } - case "setup": - for _, vvv := range vv.(map[interface{}]interface{}) { - for _, vvvv := range vvv.([]interface{}) { - t.Setup = append(t.Setup, NewAction(vvvv.(map[interface{}]interface{})["do"])) - } - } - case "teardown": - for _, vvv := range vv.(map[interface{}]interface{}) { - for _, vvvv := range vvv.([]interface{}) { - t.Teardown = append(t.Teardown, NewAction(vvvv.(map[interface{}]interface{})["do"])) - } - } - case "set": - for _, vvv := range vv.(map[interface{}]interface{}) { - steps = append(steps, NewStash(vvv)) - } - case "transform_and_set": - for _, vvv := range vv.(map[interface{}]interface{}) { - // NOTE: `set_and_transform` has flipped ordering of key and value, compared to `set` - key := utils.MapValues(vvv)[0] - val := utils.MapKeys(vvv)[0] - payload := make(map[interface{}]interface{}) - payload[key] = val - // fmt.Println(payload) - steps = append(steps, NewStash(payload)) - } - case "do": - for _, vvv := range vv.(map[interface{}]interface{}) { - steps = append(steps, NewAction(vvv)) - } - case "is_true", "is_false", "match", "lt", "gt", "lte", "gte": - for kkk, vvv := range vv.(map[interface{}]interface{}) { - steps = append(steps, NewAssertion(kkk.(string), vvv)) - } - // TODO: "length" operator - } - } - - if !ts.Skip { - t.Name = strings.ReplaceAll(k.(string), `"`, `'`) - t.Filepath = payload.Filepath - t.OrigName = k.(string) - t.Steps = steps - - ts.Tests = append(ts.Tests, t) - } - } - } - } - - return ts -} - -// NewAction returns a new action from the payload. -// -func NewAction(payload interface{}) Action { - defer func() { - if r := recover(); r != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", r) - fmt.Fprintf(os.Stderr, "Payload: %v\n", payload) - } - }() - - var a Action - a.payload = payload - a.headers = make(map[string]string) - - for k, v := range payload.(map[interface{}]interface{}) { - switch k { - case "catch": - a.catch = v.(string) - case "warnings", "allowed_warnings", "allowed_warnings_regex", "node_selector", "arbitrary_key": - continue - case "headers": - for kk, vv := range v.(map[interface{}]interface{}) { - a.headers[kk.(string)] = vv.(string) - } - default: - a.method = k.(string) - a.params = v.(map[interface{}]interface{}) - } - } - - return a -} - -// NewAssertion returns a new assertion from the payload. -// -func NewAssertion(operation string, payload interface{}) Assertion { - return Assertion{operation: operation, payload: payload} -} - -// NewStash returns a new stash from the payload. -// -func NewStash(payload interface{}) Stash { - return Stash{payload: payload} -} - -// Name returns a human name for the test suite. -// -func (ts TestSuite) Name() string { - var b strings.Builder - for _, v := range strings.Split(ts.Dir, ".") { - b.WriteString(strings.Title(v)) - } - - bname := reFilename.ReplaceAllString(filepath.Base(ts.Filepath), "$1") - for _, v := range strings.Split(bname, "_") { - b.WriteString(strings.Title(v)) - } - return strings.ReplaceAll(b.String(), "-", "") -} - -// Filename returns a suitable filename for the test suite. -// -func (ts TestSuite) Filename() string { - var b strings.Builder - - b.WriteString(strings.ToLower(strings.Replace(ts.Dir, ".", "_", -1))) - b.WriteString("__") - - bname := reFilename.ReplaceAllString(filepath.Base(ts.Filepath), "$1") - b.WriteString(strings.ToLower(bname)) - - return b.String() -} - -// SkipEsVersion returns true if the test suite should be skipped. -// -func (ts TestSuite) SkipEsVersion(minmax string) bool { - return skipVersion(minmax) -} - -// BaseFilename extracts and returns the test filename in form of `foo/bar/10_qux.yml`. -// -func (t Test) BaseFilename() string { - parts := reBaseFilename.FindStringSubmatch(t.Filepath) - if len(parts) < 1 { - panic(fmt.Sprintf("Unexpected parts for path [%s]: %s", t.Filepath, parts)) - } - return strings.TrimPrefix(parts[1], string(filepath.Separator)) -} - -// SkipEsVersion returns true if the test should be skipped. -// -func (t Test) SkipEsVersion(minmax string) bool { - return skipVersion(minmax) -} - -// ContainsAssertion returns true when the set of steps -// contain an assertion, or a specific assertion. -// -func (s Steps) ContainsAssertion(keys ...string) bool { - for _, step := range s { - if a, ok := step.(Assertion); ok { - // No keys, any assertion matches - if len(keys) < 1 { - return true - } - for _, key := range keys { - // Operation matches the key - if a.operation == key { - return true - } - if a.operation == "match" && key == "match-regexp" { - // Does any value look like a regexp? - val := utils.MapValues(a.payload)[0] - if val, ok := val.(string); ok { - if strings.HasPrefix(val, "/") { - return true - } - } - } - } - } - } - return false -} - -// ContainsCatch returns true when the set of steps contains the "catch" clause. -// -func (s Steps) ContainsCatch(keys ...string) bool { - for _, step := range s { - if a, ok := step.(Action); ok { - if a.catch != "" { - return true - } - } - } - return false -} - -// ContainsStash returns true when the set of steps contains the "set" clause. -// -func (s Steps) ContainsStash(keys ...string) bool { - for _, step := range s { - if _, ok := step.(Stash); ok { - return true - } - } - return false -} - -// Method returns the API method name for the action. -// -func (a Action) Method() string { - return utils.NameToGo(a.method) -} - -// Request returns the API request name for the action. -// -func (a Action) Request() string { - var rParts []string - parts := strings.Split(a.method, ".") - for _, p := range parts { - rParts = append(rParts, utils.NameToGo(p)) - } - return strings.Join(rParts, "") + "Request" -} - -// Params returns a map of parameters for the action. -// -func (a Action) Params() map[string]interface{} { - var kk string - out := make(map[string]interface{}) - for k, v := range a.params { - switch k.(string) { - case "context": - kk = "ScriptContext" - case "q": - kk = "Query" - case "ignore": - // TODO: Properly handle ignoring status codes - continue - default: - kk = utils.NameToGo(k.(string), utils.APIToGo(a.method)) - } - switch v.(type) { - case bool: - out[kk] = v.(bool) - case string: - out[kk] = v.(string) - case int: - out[kk] = v.(int) - case float64: - out[kk] = v.(float64) - default: - out[kk] = v - } - } - - return out -} - -// Condition returns the condition for the assertion. -// -// TODO: Evaulate https://godoc.org/github.com/google/go-cmp/cmp -// -func (a Assertion) Condition() string { - var ( - output string - - subject string - expected string - operator string - ) - - switch a.operation { - - // ================================================================================ - case "is_true": - subject = expand(a.payload.(string)) - nilGuard := catchnil(subject) - - if subject != "mapi" && subject != "slic" { - output = `if !(` + nilGuard + ") {\n" - output += `switch ` + escape(subject) + `.(type) { -case bool: - assertion = (` + escape(subject) + ` == true) -case string: - assertion = (` + escape(subject) + `.(string) != ` + `""` + `) -case int: - assertion = (` + escape(subject) + `.(int) != 0) -case float64: - assertion = (` + escape(subject) + `.(float64) != 0) -case encjson.Number: - assertion = (` + escape(subject) + `.(encjson.Number).String() != "0") -default: - assertion = (` + escape(subject) + ` != nil) -}` + "\n" - output += "} else {\n" - output += "assertion = true}\n" - output += `if !assertion` + " {\n" - } else { - // if subject == "slic" { - // output = `if fmt.Sprintf("%v", ` + subject + `) == fmt.Sprintf("%v", []interface{}{}) {` + "\n" - // } else { - // output = `if fmt.Sprintf("%v", ` + subject + `) == fmt.Sprintf("%v", map[string]interface{}{}) {` + "\n" - // } - output = `if ` + subject + ` == nil {` + "\n" - } - return output - - // ================================================================================ - case "is_false": - subject = expand(a.payload.(string)) - nilGuard := catchnil(subject) - - if subject != "mapi" && subject != "slic" { - output = `if !(` + nilGuard + ") {\n" - output += `switch ` + escape(subject) + `.(type) { -case bool: - assertion = (` + escape(subject) + ` == false) -case string: - assertion = (` + escape(subject) + `.(string) == ` + `""` + `) -case int: - assertion = (` + escape(subject) + `.(int) == 0) -case float64: - assertion = (` + escape(subject) + `.(float64) == 0) -case encjson.Number: - assertion = (` + escape(subject) + `.(encjson.Number).String() == "0") -default: - assertion = (` + escape(subject) + ` == nil) -}` + "\n" - output += "} else {\n" - output += "assertion = true}\n" - output += `if !assertion` + " {\n" - } else { - if subject == "slic" { - output = `if fmt.Sprintf("%v", ` + subject + `) != fmt.Sprintf("%v", []interface{}{}) {` + "\n" - } else { - output = `if fmt.Sprintf("%v", ` + subject + `) != fmt.Sprintf("%v", map[string]interface{}{}) {` + "\n" - } - } - return output - - // ================================================================================ - case "lt", "gt", "lte", "gte": - key := utils.MapKeys(a.payload)[0] - - subject = expand(key) - expected = fmt.Sprintf("%v", utils.MapValues(a.payload)[0]) - - nilGuard := catchnil(subject) - - // Is the value a stash value? - if strings.HasPrefix(fmt.Sprintf("%v", utils.MapValues(a.payload)[0]), "$") { - expected = `stash[` + strconv.Quote(expected) + `].(encjson.Number).Float64()` - } else { - expected = `float64(` + expected + `), struct{}{}` - } - - switch a.operation { - case "lt": - operator = "<" - case "gt": - operator = ">" - case "lte": - operator = "<=" - case "gte": - operator = ">=" - } - - r := strings.NewReplacer(`"`, "", `\`, "") - rkey := r.Replace(key) - output += ` if ` + nilGuard + ` { t.Error("Expected [` + rkey + `] to not be nil") } - actual, _ = ` + escape(subject) + `.(encjson.Number).Float64() - expected, _ = ` + expected + ` - assertion = actual.(float64) ` + operator + ` expected.(float64) - if !assertion { - t.Logf("%v != %v", actual, expected)` + "\n" - - return output - - // ================================================================================ - case "match": - var b strings.Builder - - key := utils.MapKeys(a.payload)[0] - val := utils.MapValues(a.payload)[0] - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // 1. Match on body - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - if key == "$body" { - expected = strings.TrimSpace(fmt.Sprintf("%v", val)) - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // 1a. Is the expected value a regex pattern? - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - if strings.HasPrefix(expected, "/") { - // TODO: Refactor - var pattern string - pattern = expected - - // Remove all comments - reComment := regexp.MustCompile(`#\s*[^\n]+`) - pattern = reComment.ReplaceAllString(pattern, "") - - // Remove the prefix and suffix slashes - pattern = strings.TrimPrefix(pattern, "/") - pattern = strings.TrimSuffix(pattern, "/") - - // Remove the new lines - pattern = strings.Replace(pattern, "\n", "", -1) - - // Remove whitespace (can be preceded by slash, eg. cat.templates/10_basic.yml:255) - reWhitespace := regexp.MustCompile(`\\*\s+`) - pattern = reWhitespace.ReplaceAllString(pattern, `\s*`) - - b.WriteString(`re, err = regexp.Compile("(?m)" + ` + "`" + pattern + "`" + `) - if err != nil { - t.Fatalf("Regex compile error: %s", err) - } - - match = re.Match(body)` + "\n") - b.WriteString(` if !match` + " {\n") - return b.String() - } else { - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // 1b. Is the expected value a literal value - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // TODO: Match on literal value - // output = fmt.Sprintf("if true { // TODO, MatchBodyLiteral: %s => %v\n", a.operation, a.payload) - output = `if strings.HasPrefix(string(body), "[") { - match = !reflect.DeepEqual(fmt.Sprintf("%#v", slic), ` + fmt.Sprintf("%#v", val) + `) - } else { - match = !reflect.DeepEqual(fmt.Sprintf("%#v", mapi), ` + fmt.Sprintf("%#v", val) + `) - } - if !match {` + "\n" - return output - } - - // panic(fmt.Sprintf("MatchUnknown: %q => %v\n", a.operation, a.payload)) - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // 2. Match on JSON/YAML field or numbered item - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - } else { - subject = expand(key) - expected = strings.TrimSpace(fmt.Sprintf("%v", val)) - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // 2a. Is the expected value a regex pattern? - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - if strings.HasPrefix(expected, "/") { - var pattern string - pattern = expected - pattern = strings.Replace(pattern, "/", "", -1) - pattern = strings.Replace(pattern, "\n", "", -1) - pattern = strings.Replace(pattern, " ", `\s*`, -1) - - b.WriteString(`re, err = regexp.Compile("(?m)" + ` + "`" + pattern + "`" + `) - if err != nil { - t.Fatalf("Regex compile error: %s", err) - } - - match = re.MatchString(fmt.Sprintf("%v", ` + escape(subject) + `))` + "\n") - b.WriteString(` if !match` + " {\n") - return b.String() - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // 2b. Is the value a regular value? - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - } else { - // fmt.Printf("subject: %s, val: %T, %v \n", subject, val, val) - - nilGuard := catchnil(subject) - switch val.(type) { - - // -------------------------------------------------------------------------------- - case nil: - output += ` if ` + escape(subject) + ` != nil` + " {\n" - - // -------------------------------------------------------------------------------- - case bool: - output += ` if ` + - nilGuard + - " || \n" + - `fmt.Sprintf("%v", ` + escape(subject) + `) != ` + - `fmt.Sprintf("%v", ` + expected + `)` + - " {\n" - case int, float64: - r := strings.NewReplacer(`"`, "", `\`, "") - rkey := r.Replace(key) - output += ` if ` + nilGuard + ` { t.Error("Expected [` + rkey + `] to not be nil") } - actual = ` + escape(subject) + ` - if intValue, ok := actual.(int); ok { - actual = fmt.Sprint(intValue) - } else { - actual = actual.(encjson.Number).String() - } - expected = ` + expected + ` - // TEMP: Hack to prevent 1.0 != 1 errors - if strings.HasSuffix(actual.(string), ".0") { - actual = strings.TrimSuffix(actual.(string), ".0") - expected = strings.TrimSuffix(` + strconv.Quote(expected) + `, ".0") - } - assertion = fmt.Sprintf("%v", actual) == fmt.Sprintf("%v", expected) - if !assertion { - t.Logf("%v != %v", actual, expected)` + "\n" - - // -------------------------------------------------------------------------------- - case string: - output += ` if ` + - nilGuard + - " || \n" + - `strings.TrimSpace(fmt.Sprintf("%s", ` + escape(subject) + `)) != ` - if strings.HasPrefix(expected, "$") { - output += `strings.TrimSpace(fmt.Sprintf("%s", ` + `stash["` + expected + `"]` + `))` - } else { - output += `strings.TrimSpace(fmt.Sprintf("%s", ` + strconv.Quote(expected) + `))` - } - output += " {\n" - - // -------------------------------------------------------------------------------- - case map[interface{}]interface{}, map[string]interface{}: - // We cannot reliably serialize to json and compare the json outputs: YAML responses are parsed as - // a map[interface{}]interface{} that encoding/json fails to marshall - // See https://play.golang.org/p/jhcXwg5dIrn - expectedPayload := fmt.Sprintf("%#v", val) - expectedPayload = strings.ReplaceAll(expectedPayload, "map[interface {}]interface {}", "map[string]interface {}") - output = ` actual = fmt.Sprintf("%v",` + escape(subject) + `) - expected = fmt.Sprintf("%v",` + expectedPayload + `) - if actual != expected {` + "\n" - - // -------------------------------------------------------------------------------- - case []interface{}: - expectedPayload := fmt.Sprintf("%#v", val) - expectedPayload = strings.ReplaceAll(expectedPayload, "map[interface {}]interface {}", "map[string]interface {}") - output = ` actual, _ = encjson.Marshal(` + escape(subject) + `) - expected, _ = encjson.Marshal(` + expectedPayload + `) - if fmt.Sprintf("%s", actual) != fmt.Sprintf("%s", expected) {` + "\n" - - // -------------------------------------------------------------------------------- - default: - output += ` if true { // TODO, MatchMissingType: ` + fmt.Sprintf("<%[1]T>%[1]v", val) + "\n" - output += ` // Subject: ` + subject + "\n" - output += ` // Value: ` + fmt.Sprintf("%#v", val) + "\n" - } - - return output - } - } - - // ================================================================================ - default: - return fmt.Sprintf("if true { // TODO, Unimplemented: %q => %v\n", a.operation, a.payload) - } - - // panic(fmt.Sprintf("Unreachable: %q => %v", a.operation, a.payload)) -} - -// Error returns an error handling for the failed assertion. -// -func (a Assertion) Error() string { - var ( - output string - - subject string - expected string - ) - - output = `Unexpected value; <` + a.operation + `> : ` + fmt.Sprintf("%s", escape(a.payload)) - - switch a.operation { - case "is_true": - subject = expand(a.payload.(string)) - output = `Expected ` + escape(subject) + ` to be truthy` - - case "is_false": - subject = expand(a.payload.(string)) - output = `Expected ` + escape(subject) + ` to be falsey` - - case "lt", "gt", "lte", "gte": - subject = expand(utils.MapKeys(a.payload)[0]) - expected = fmt.Sprintf("%v", utils.MapValues(a.payload)[0]) - output = `Expected ` + escape(utils.MapKeys(a.payload)[0]) + ` ` + a.operation + ` ` + escape(expected) - - case "length": - panic(fmt.Sprintf("TODO: length: %s", a.payload)) - - case "match": - key := utils.MapKeys(a.payload)[0] - val := utils.MapValues(a.payload)[0] - - expected := strings.TrimSpace(fmt.Sprintf("%v", val)) - - if key == "$body" { // 1. Match on body - - if strings.HasPrefix(expected, "/") { - return `t.Errorf("Expected [$body] to match pattern: %s", re)` - } else { - output = `Expected [$body] to match value: ` + escape(expected) - } - - } else { // 2. Match on JSON/YAML field or numbered item - if key == "" { - key = "response" - } - - if strings.HasPrefix(expected, "/") { // 2a. Is the value to match a regex? - expected = strings.Replace(expected, "\n", "
", -1) - expected = strings.Replace(expected, `/`, `|`, -1) - - return `t.Errorf("Expected [` + strings.Trim(strconv.Quote(escape(key)), `"`) + `] to match pattern: %s", re)` - } else { // 2b. Is the value to match a regular value? - output = `Expected [` + strings.Trim(strconv.Quote(escape(key)), `"`) + `] to match '` + escape(expected) + `'` - } - } - } - - return `t.Error(` + strconv.Quote(output) + `)` -} - -// Key returns the stash key as a string. -// -func (s Stash) Key() string { - vals := utils.MapValues(s.payload) - if len(vals) < 1 { - return "" - } - - return fmt.Sprintf("$%s", vals[0]) -} - -// Value returns the stash value as a string. -// -func (s Stash) Value() string { - vals := utils.MapKeys(s.payload) - if len(vals) < 1 { - return "" - } - - return expand(fmt.Sprintf("%v", vals[0])) -} - -// expand "unwraps" a field name like `foo.bar.0.baz` into a proper Go structure -// -func expand(s string, format ...string) string { - var ( - b bytes.Buffer - - container string - ) - - // Handle the "literal dot" in a fieldname - s = strings.Replace(s, `\.`, `_~_|_~_`, -1) - - parts := strings.Split(s, ".") - - if len(parts) > 0 { - if reNumber.MatchString(parts[0]) { - container = "slic" - } else { - container = "mapi" - } - } else { - container = "mapi" - } - - b.WriteString(container) - - if len(parts) > 0 && parts[0] == "" { - return b.String() - } - - for i, v := range parts { - if reNumber.MatchString(v) { - if i > 0 { - b.WriteString(`.([]interface{})`) - } - b.WriteString(`[`) - b.WriteString(v) - b.WriteString(`]`) - } else { - if i > 0 { - if len(format) > 0 && format[0] == "yaml" { - b.WriteString(`.(map[interface{}]interface{})`) - } else { - b.WriteString(`.(map[string]interface{})`) - } - } - b.WriteString(`["`) - b.WriteString(strings.Trim(v, `"`)) // Remove the quotes from keys - b.WriteString(`"]`) - } - - } - return strings.Replace(b.String(), `_~_|_~_`, `\.`, -1) -} - -// catchnil returns a condition which expands the input and checks if any part is not nil. -// -func catchnil(input string) string { - var output string - - parts := strings.Split(strings.Replace(input, `\.`, `_~_|_~_`, -1), ".") - for i := range parts { - output += strings.Join(parts[:i+1], ".") + " == nil" - if i+1 < len(parts) { - output += " ||\n\t\t" - } - } - output = strings.Replace(output, `_~_|_~_`, `.`, -1) - - return output -} - -// escape replaces unsafe characters in strings -// -func escape(s interface{}) string { - if s, ok := s.(string); ok { - // s = strings.Replace(s, `"`, `'`, -1) - // s = strings.Replace(s, `\`, `\\`, -1) - s = strings.Replace(s, `\.`, `.`, -1) - return s - } - return fmt.Sprintf("%s", s) -} - -// skipVersion parses minmax string and returns -// true when EsVersion is in the range. -// -func skipVersion(minmax string) bool { - versions := strings.Split(minmax, "-") - if len(versions) < 2 { - panic(fmt.Sprintf("skipVersion: Unexpected input: %q", minmax)) - } - - min, max := strings.TrimSpace(versions[0]), strings.TrimSpace(versions[1]) - - if max == "" { // Skip when max version is not set - return true - } - - if EsVersion >= min && EsVersion <= max { - return true - } - - return false -} diff --git a/internal/build/cmd/generate/commands/gentests/patches.go b/internal/build/cmd/generate/commands/gentests/patches.go deleted file mode 100644 index f4cad918c..000000000 --- a/internal/build/cmd/generate/commands/gentests/patches.go +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gentests - -import ( - "bytes" - "io" - "io/ioutil" - "regexp" - "strings" -) - -var ( - rePatchShardKeys = regexp.MustCompile(`shards\.(\d+)\.(\d+)`) - rePatchShardStoresKeys = regexp.MustCompile(`shards\.(\d+)\.stores\.(\d+)`) - rePatchBucketKeys = regexp.MustCompile(`aggregations.(\d+).(\d+).buckets`) -) - -// PatchTestSource performs a regex based patching of the input. -// -func PatchTestSource(fpath string, r io.Reader) (io.Reader, error) { - c, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - - // Patch the path to a shard by adding quotes around the shard number, - // which is a map key, not an array index. - for _, p := range []string{ - "indices.flush/10_basic.yml", - "indices.put_template/10_basic.yml", - "indices.recovery/10_basic.yml", - "indices.segments/10_basic.yml", - "indices.shard_stores/10_basic.yml", - "indices.stats/12_level.yml", - } { - if strings.Contains(fpath, p) { - c = rePatchShardKeys.ReplaceAll(c, []byte(`shards."$1".$2`)) - c = rePatchShardStoresKeys.ReplaceAll(c, []byte(`shards."$1".stores.$2`)) - } - } - - for _, p := range []string{ - "search.aggregation/230_composite.yml", - } { - if strings.Contains(fpath, p) { - c = rePatchBucketKeys.ReplaceAll(c, []byte(`aggregations."$1"."$2".buckets`)) - } - } - - return bytes.NewReader(c), nil -} diff --git a/internal/build/cmd/generate/commands/gentests/skips.go b/internal/build/cmd/generate/commands/gentests/skips.go deleted file mode 100644 index 15313d811..000000000 --- a/internal/build/cmd/generate/commands/gentests/skips.go +++ /dev/null @@ -1,165 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package gentests - -import ( - "fmt" - "strings" - - "gopkg.in/yaml.v2" -) - -var skipTests map[string][]string - -func init() { - err := yaml.NewDecoder(strings.NewReader(skipTestsYAML)).Decode(&skipTests) - if err != nil { - panic(fmt.Sprintf("ERROR: %v", err)) - } -} - -var skipFiles = []string{ - "update/85_fields_meta.yml", // Uses non-existing API property - "update/86_fields_meta_with_types.yml", // --||-- - - "search.highlight/20_fvh.yml", // bad backslash -} - -// TODO: Comments into descriptions for `Skip()` -// -var skipTestsYAML = ` ---- -# Cannot distinguish between missing value for refresh and an empty string -bulk/50_refresh.yml: - - refresh=empty string immediately makes changes are visible in search -bulk/51_refresh_with_types.yml: - - refresh=empty string immediately makes changes are visible in search -create/60_refresh.yml: - - When refresh url parameter is an empty string that means "refresh immediately" -create/61_refresh_with_types.yml: - - When refresh url parameter is an empty string that means "refresh immediately" -delete/50_refresh.yml: - - When refresh url parameter is an empty string that means "refresh immediately" -delete/51_refresh_with_types.yml: - - When refresh url parameter is an empty string that means "refresh immediately" -index/60_refresh.yml: - - When refresh url parameter is an empty string that means "refresh immediately" -index/61_refresh_with_types.yml: - - When refresh url parameter is an empty string that means "refresh immediately" -update/60_refresh.yml: - - When refresh url parameter is an empty string that means "refresh immediately" -update/61_refresh_with_types.yml: - - When refresh url parameter is an empty string that means "refresh immediately" - -# Stash in value -cluster.reroute/11_explain.yml: -nodes.info/30_settings.yml: -nodes.stats/20_response_filtering.yml: -nodes.stats/30_discovery.yml: - - Discovery stats -nodes.discovery/30_discovery.yml: - - Discovery stats - -# Arbitrary key -indices.shrink/10_basic.yml: -indices.shrink/20_source_mapping.yml: -indices.shrink/30_copy_settings.yml: -indices.split/30_copy_settings.yml: -nodes.info/10_basic.yml: -nodes.reload_secure_settings/10_basic.yml: -nodes.stats/50_indexing_pressure.yml: -nodes.stats/40_store_stats.yml: - - Store stats - -# Parsed response is YAML: value is map[interface {}]interface {}, not map[string]interface {} -cat.aliases/20_headers.yml: - - Simple alias with yaml body through Accept header - -# Incorrect int instead of float in match (aggregations.date_range.buckets.0.from: 1000000); TODO: PR -search.aggregation/40_range.yml: - - Date range - -# Mismatch in number parsing, 8623000 != 8.623e+06 -search.aggregation/340_geo_distance.yml: - - avg_bucket - -# Tries to match on "Cluster Get Settings" output, but that's an empty map -search/320_disallow_queries.yml: - -# No support for headers per request yet -tasks.list/10_basic.yml: - - tasks_list headers - -# Node Selector feature not implemented -cat.aliases/10_basic.yml: - - "Help (pre 7.4.0)" - - "Simple alias (pre 7.4.0)" - - "Complex alias (pre 7.4.0)" - - "Column headers (pre 7.4.0)" - - "Alias against closed index (pre 7.4.0)" - -indices.put_mapping/10_basic.yml: - - "Put mappings with explicit _doc type bwc" - -# Test fails with: [400 Bad Request] illegal_argument_exception, "template [test] has index patterns [test-*] matching patterns from existing index templates [test2,test] with patterns (test2 => [test-*],test => [test-*, test2-*]), use index templates (/_index_template) instead" -test/indices.put_template/10_basic.yml: - -# Incompatible regex -cat.templates/10_basic.yml: - - "Sort templates" - - "Multiple template" - -# Missing test setup -cluster.voting_config_exclusions/10_basic.yml: - - "Add voting config exclusion by unknown node name" - -# Not relevant -search/issue4895.yml: -search/issue9606.yml: - - -# FIXME -bulk/80_cas.yml: -bulk/81_cas_with_types.yml: - -# Cannot compare float64 ending with .0 reliably due to inconsistent serialisation (https://github.com/golang/go/issues/26363) -search/330_fetch_fields.yml: - - Test nested field inside object structure - -search/350_point_in_time.yml: - - msearch - -nodes.stats/11_indices_metrics.yml: - - Metric - http - -searchable_snapshots/10_usage.yml: - - Tests searchable snapshots usage stats with full_copy and shared_cache indices - -# Expects count 2 but returns only 1 -service_accounts/10_basic.yml: - - Test service account tokens -` diff --git a/internal/build/cmd/generate/commands/gentests/testdata/cluster.health/10_basic.yml b/internal/build/cmd/generate/commands/gentests/testdata/cluster.health/10_basic.yml deleted file mode 100644 index 70d737223..000000000 --- a/internal/build/cmd/generate/commands/gentests/testdata/cluster.health/10_basic.yml +++ /dev/null @@ -1,135 +0,0 @@ ---- -"cluster health basic test": - - do: - cluster.health: {} - - - is_true: cluster_name - - is_false: timed_out - - gte: { number_of_nodes: 1 } - - gte: { number_of_data_nodes: 1 } - - match: { active_primary_shards: 0 } - - match: { active_shards: 0 } - - match: { relocating_shards: 0 } - - match: { initializing_shards: 0 } - - match: { unassigned_shards: 0 } - - gte: { number_of_pending_tasks: 0 } - ---- -"cluster health basic test, one index": - - do: - indices.create: - index: test_index - body: - settings: - index: - number_of_replicas: 0 - - - do: - cluster.health: - wait_for_status: green - wait_for_no_relocating_shards: true - - - is_true: cluster_name - - is_false: timed_out - - gte: { number_of_nodes: 1 } - - gte: { number_of_data_nodes: 1 } - - gt: { active_primary_shards: 0 } - - gt: { active_shards: 0 } - - gte: { relocating_shards: 0 } - - match: { initializing_shards: 0 } - - match: { unassigned_shards: 0 } - - gte: { number_of_pending_tasks: 0 } - ---- -"cluster health basic test, one index with wait for active shards": - - do: - indices.create: - index: test_index - body: - settings: - index: - number_of_replicas: 0 - - - do: - cluster.health: - wait_for_active_shards: 1 - wait_for_no_relocating_shards: true - - - is_true: cluster_name - - is_false: timed_out - - gte: { number_of_nodes: 1 } - - gte: { number_of_data_nodes: 1 } - - gt: { active_primary_shards: 0 } - - gt: { active_shards: 0 } - - gte: { relocating_shards: 0 } - - match: { initializing_shards: 0 } - - match: { unassigned_shards: 0 } - - gte: { number_of_pending_tasks: 0 } - ---- -"cluster health basic test, one index with wait for all active shards": - - do: - indices.create: - index: test_index - body: - settings: - index: - number_of_replicas: 0 - - - do: - cluster.health: - wait_for_active_shards: all - wait_for_no_relocating_shards: true - - - is_true: cluster_name - - is_false: timed_out - - gte: { number_of_nodes: 1 } - - gte: { number_of_data_nodes: 1 } - - gt: { active_primary_shards: 0 } - - gt: { active_shards: 0 } - - gte: { relocating_shards: 0 } - - match: { initializing_shards: 0 } - - match: { unassigned_shards: 0 } - - gte: { number_of_pending_tasks: 0 } - ---- -"cluster health basic test, one index with wait for no initializing shards": - - skip: - version: " - 6.1.99" - reason: "wait_for_no_initializing_shards is introduced in 6.2.0" - - - do: - indices.create: - index: test_index - wait_for_active_shards: 0 - body: - settings: - index: - number_of_replicas: 0 - - - do: - cluster.health: - wait_for_no_initializing_shards: true - - - match: { initializing_shards: 0 } - ---- -"cluster health levels": - - do: - indices.create: - index: test_index - - do: - cluster.health: - level: indices - - - is_true: indices - - is_false: indices.test_index.shards - - - do: - cluster.health: - level: shards - - - is_true: indices - - is_true: indices.test_index.shards - - diff --git a/internal/build/cmd/generate/commands/gentests/testdata/info/10_basic.yml b/internal/build/cmd/generate/commands/gentests/testdata/info/10_basic.yml deleted file mode 100644 index 05109ea6c..000000000 --- a/internal/build/cmd/generate/commands/gentests/testdata/info/10_basic.yml +++ /dev/null @@ -1,44 +0,0 @@ ---- -setup: - - do: { info: {} } - - do: { info: {} } - ---- -teardown: - - do: { info: {} } - ---- -"First": - - setup: - - do: { info: {} } - - do: { info: {} } - - teardown: - - do: { cluster.health: {} } - - - do: { info: {} } - - - is_true: name - - is_true: cluster_name - - is_true: version - - is_true: version.number - - - is_false: foobar - - - match: { cluster_name: "opensearch-go" } - - - match: - version.lucene_version: /\d\.\d\.\d/ - - - match: - $body: /.*opensearch.*/ - -# Comment ---- -"Second": - - do: { info: { } } - - do: - cluster.health: - level: "indices" - pretty: true - - is_true: cluster_name - - gte: { number_of_nodes: 1 } diff --git a/internal/build/cmd/generate/commands/gentests/testdata/info/20_lucene_version.yml b/internal/build/cmd/generate/commands/gentests/testdata/info/20_lucene_version.yml deleted file mode 100644 index 83414fbab..000000000 --- a/internal/build/cmd/generate/commands/gentests/testdata/info/20_lucene_version.yml +++ /dev/null @@ -1,7 +0,0 @@ ---- -"Lucene Version": - - do: {info: {}} - - is_true: version.lucene_version - - - diff --git a/internal/build/cmd/tools/commands/spec/command.go b/internal/build/cmd/tools/commands/spec/command.go deleted file mode 100644 index 6e59ff0cf..000000000 --- a/internal/build/cmd/tools/commands/spec/command.go +++ /dev/null @@ -1,315 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package cmd - -import ( - "archive/zip" - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "log" - "net/http" - "net/url" - "os" - "path/filepath" - "strings" - "time" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd" - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" - "github.com/opensearch-project/opensearch-go/v2/internal/version" - "github.com/spf13/cobra" -) - -var ( - output *string - commitHash *string - debug *bool - info *bool -) - -func init() { - output = toolsCmd.Flags().StringP("output", "o", "", "Path to a folder for generated output") - commitHash = toolsCmd.Flags().StringP("commit_hash", "c", "", "OpenSearch commit hash") - debug = toolsCmd.Flags().BoolP("debug", "d", false, "Print the generated source to terminal") - info = toolsCmd.Flags().Bool("info", false, "Print the API details to terminal") - - cmd.RegisterCmd(toolsCmd) -} - -var toolsCmd = &cobra.Command{ - Use: "download-spec", - Short: "Download specification artifact for code & tests generation", - Run: func(cmd *cobra.Command, args []string) { - command := &Command{ - Output: *output, - CommitHash: *commitHash, - Debug: *debug, - Info: *info, - } - err := command.Execute() - if err != nil { - utils.PrintErr(err) - os.Exit(1) - } - }, -} - -type Command struct { - Output string - CommitHash string - Debug bool - Info bool -} - -// download-spec retrieve the list of active artifacts -// downloads, extract and write to disk the rest-resources spec alongside a json with relevant build information. -func (c Command) Execute() (err error) { - artifactsUrl := os.Getenv("OPENSEARCH_ARTIFACTS_URL") - - buildVersion := os.Getenv("OPENSEARCH_BUILD_VERSION") - if buildVersion == "" { - buildVersion = version.Client - } - - versionUrl := strings.Join([]string{artifactsUrl, buildVersion}, "/") - - res, err := http.Get(versionUrl) - if err != nil { - log.Fatalf(err.Error()) - } - defer res.Body.Close() - - var v Versions - dec := json.NewDecoder(res.Body) - err = dec.Decode(&v) - if err != nil { - log.Fatalf(err.Error()) - } - - if c.Debug { - log.Printf("%d builds found", len(v.Version.Builds)) - } - - var build Build - if c.CommitHash != "" { - if build, err = findBuildByCommitHash(c.CommitHash, v.Version.Builds); err != nil { - build = findMostRecentBuild(v.Version.Builds) - } - } else { - build = findMostRecentBuild(v.Version.Builds) - } - if c.Debug { - log.Printf("Build found : %s", build.Projects.OpenSearch.CommitHash) - } - - data, err := c.downloadZip(build) - if err != nil { - log.Fatalf("Cannot download zip from %s, reason : %s", build.zipfileUrl(), err) - } - - if err := c.extractZipToDest(data); err != nil { - log.Fatalf(err.Error()) - } - - d, _ := json.Marshal(build) - - err = c.writeFileToDest("opensearch.json", d) - if err != nil { - log.Fatalf(err.Error()) - } - - return nil -} - -func (c Command) writeFileToDest(filename string, data []byte) error { - path := filepath.Join(c.Output, filename) - if err := ioutil.WriteFile(path, data, 0644); err != nil { - return fmt.Errorf("cannot write file: %s", err) - } - if c.Debug { - log.Printf("Successfuly written file to : %s", path) - } - return nil -} - -type Versions struct { - Version struct { - Builds []Build `json:"builds"` - } `json:"version"` -} - -type PackageUrl struct { - *url.URL -} - -func (p *PackageUrl) UnmarshalJSON(data []byte) error { - if string(data) == "null" { - return nil - } - url, err := url.Parse(string(data[1 : len(data)-1])) - if err == nil { - p.URL = url - } - return err -} - -type BuildStartTime struct { - *time.Time -} - -func (t *BuildStartTime) UnmarshalJSON(data []byte) error { - if string(data) == "null" { - return nil - } - var err error - parsedTime, err := time.Parse(`"`+"Mon, 2 Jan 2006 15:04:05 MST"+`"`, string(data)) - t.Time = &parsedTime - return err -} - -type Build struct { - StartTime BuildStartTime `json:"start_time"` - Version string `json:"version"` - BuildId string `json:"build_id"` - Projects struct { - OpenSearch struct { - Branch string `json:"branch"` - CommitHash string `json:"commit_hash"` - Packages map[string]struct { - Url PackageUrl `json:"url"` - Type string `json:"type"` - } - } `json:"opensearch"` - } `json:"projects"` -} - -func NewBuild() Build { - t := time.Date(1970, 0, 0, 0, 0, 0, 0, time.UTC) - startTime := BuildStartTime{Time: &t} - return Build{StartTime: startTime} -} - -// zipfileUrl return the file URL for the rest-resources artifact from Build -// There should be only one artifact matching the requirements par Build. -func (b Build) zipfileUrl() string { - for _, pack := range b.Projects.OpenSearch.Packages { - if pack.Type == "zip" && strings.Contains(pack.Url.String(), "rest-resources") { - return pack.Url.String() - } - } - return "" -} - -// extractZipToDest extract the data from a previously downloaded file loaded in memory to Output target. -func (c Command) extractZipToDest(data []byte) error { - zipReader, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) - if err != nil { - return err - } - - if err = os.MkdirAll(c.Output, 0744); err != nil { - return fmt.Errorf("cannot created destination directory: %s", err) - } - - for _, file := range zipReader.File { - f, err := file.Open() - if err != nil { - return fmt.Errorf("cannot read file in zipfile: %s", err) - } - - if file.FileInfo().IsDir() { - path := filepath.Join(c.Output, file.Name) - _ = os.MkdirAll(path, 0744) - } else { - data, err := ioutil.ReadAll(f) - if err != nil { - return err - } - - if err := c.writeFileToDest(file.Name, data); err != nil { - return err - } - } - } - - if c.Debug { - log.Printf("Zipfile successfully extracted to %s", c.Output) - } - - return nil -} - -// downloadZip fetches the rest-resources artifact from a Build and return its content as []byte. -func (c Command) downloadZip(b Build) ([]byte, error) { - url := b.zipfileUrl() - if c.Debug { - log.Printf("Zipfile url : %s", b.zipfileUrl()) - } - - client := &http.Client{} - - req, err := http.NewRequest(http.MethodGet, url, nil) - if err != nil { - return nil, err - } - - req.Header.Add("Accept-Content", "gzip") - res, err := client.Do(req) - if err != nil { - return nil, err - } - defer res.Body.Close() - - data, _ := ioutil.ReadAll(res.Body) - return data, err -} - -// findMostRecentBuild iterates through the builds retrieved from the api -// and return the latest one based on the StartTime of each Build. -func findMostRecentBuild(builds []Build) Build { - var latestBuild Build - latestBuild = NewBuild() - for _, build := range builds { - if build.StartTime.After(*latestBuild.StartTime.Time) { - latestBuild = build - } - } - return latestBuild -} - -// findBuildByCommitHash iterates through the builds and returns the first occurrence of Build -// that matches the provided commitHash. -func findBuildByCommitHash(commitHash string, builds []Build) (Build, error) { - for _, build := range builds { - if build.Projects.OpenSearch.CommitHash == commitHash { - return build, nil - } - } - return Build{}, fmt.Errorf("Build with commit hash %s not found", commitHash) -} diff --git a/internal/build/cmd/tools/commands/spec/command_test.go b/internal/build/cmd/tools/commands/spec/command_test.go deleted file mode 100644 index 5b647e69b..000000000 --- a/internal/build/cmd/tools/commands/spec/command_test.go +++ /dev/null @@ -1,75 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package cmd - -import ( - "encoding/json" - "testing" -) - -func TestBuild_zipfileUrl(t *testing.T) { - tests := []struct { - name string - json string - want string - }{ - { - name: "Simple test with valid url", - json: ` - { - "start_time": "Mon, 19 Apr 2021 12:15:47 GMT", - "version": "1.0.0-SNAPSHOT", - "build_id": "1.0.0-ab7cd914", - "projects": { - "opensearch": { - "branch": "main", - "commit_hash": "d3be79018b5b70a118ea5a897a539428b728df5a", - "Packages": { - "rest-resources-zip-8.0.0-SNAPSHOT.zip": { - "url": "https://artifacts.opensearch.org/rest-resources-zip-1.0.0-SNAPSHOT.zip", - "type": "zip" - } - } - } - } - } - `, - want: "https://artifacts.opensearch.org/rest-resources-zip-1.0.0-SNAPSHOT.zip", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - b := Build{} - if err := json.Unmarshal([]byte(tt.json), &b); err != nil { - t.Fatalf(err.Error()) - } - if got := b.zipfileUrl(); got != tt.want { - t.Errorf("zipfileUrl() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/internal/build/go.mod b/internal/build/go.mod deleted file mode 100644 index 33f9a8097..000000000 --- a/internal/build/go.mod +++ /dev/null @@ -1,16 +0,0 @@ -module github.com/opensearch-project/opensearch-go/v2/internal/build - -go 1.15 - -replace github.com/opensearch-project/opensearch-go/v2 => ../../ - -require ( - github.com/alecthomas/chroma v0.8.2 - github.com/kr/pretty v0.1.0 // indirect - github.com/opensearch-project/opensearch-go/v2 v2.2.0 - github.com/spf13/cobra v1.6.1 - golang.org/x/crypto v0.1.0 - golang.org/x/tools v0.1.12 - gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect - gopkg.in/yaml.v2 v2.4.0 -) diff --git a/internal/build/go.sum b/internal/build/go.sum deleted file mode 100644 index 6522dd92a..000000000 --- a/internal/build/go.sum +++ /dev/null @@ -1,112 +0,0 @@ -github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38 h1:smF2tmSOzy2Mm+0dGI2AIUHY+w0BUc+4tn40djz7+6U= -github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI= -github.com/alecthomas/chroma v0.8.2 h1:x3zkuE2lUk/RIekyAJ3XRqSCP4zwWDfcw/YJCuCAACg= -github.com/alecthomas/chroma v0.8.2/go.mod h1:sko8vR34/90zvl5QdcUdvzL3J8NKjAUx9va9jPuFNoM= -github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721 h1:JHZL0hZKJ1VENNfmXvHbgYlbUOvpzYzvy2aZU5gXVeo= -github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= -github.com/alecthomas/kong v0.2.4/go.mod h1:kQOmtJgV+Lb4aj+I2LEn40cbtawdWJ9Y8QLq+lElKxE= -github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897 h1:p9Sln00KOTlrYkxI1zYWl1QLnEqAqEARBEYa8FQnQcY= -github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ= -github.com/aws/aws-sdk-go v1.44.205/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= -github.com/aws/aws-sdk-go-v2 v1.17.5/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= -github.com/aws/aws-sdk-go-v2/config v1.18.15/go.mod h1:vS0tddZqpE8cD9CyW0/kITHF5Bq2QasW9Y1DFHD//O0= -github.com/aws/aws-sdk-go-v2/credentials v1.13.15/go.mod h1:vRMLMD3/rXU+o6j2MW5YefrGMBmdTvkLLGqFwMLBHQc= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.23/go.mod h1:mOtmAg65GT1HIL/HT/PynwPbS+UG0BgCZ6vhkPqnxWo= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.29/go.mod h1:Dip3sIGv485+xerzVv24emnjX5Sg88utCL8fwGmCeWg= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.23/go.mod h1:mr6c4cHC+S/MMkrjtSlG4QA36kOznDep+0fga5L/fGQ= -github.com/aws/aws-sdk-go-v2/internal/ini v1.3.30/go.mod h1:vsbq62AOBwQ1LJ/GWKFxX8beUEYeRp/Agitrxee2/qM= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.23/go.mod h1:9uPh+Hrz2Vn6oMnQYiUi/zbh3ovbnQk19YKINkQny44= -github.com/aws/aws-sdk-go-v2/service/sso v1.12.4/go.mod h1:jtLIhd+V+lft6ktxpItycqHqiVXrPIRjWIsFIlzMriw= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.4/go.mod h1:zVwRrfdSmbRZWkUkWjOItY7SOalnFnq/Yg2LVPqDjwc= -github.com/aws/aws-sdk-go-v2/service/sts v1.18.5/go.mod h1:1mKZHLLpDMHTNSYPJ7qrcnCQdHCWsNQaT0xRvq2u80s= -github.com/aws/smithy-go v1.13.5/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 h1:y5HC9v93H5EPKqaS1UYVg1uYah5Xf51mBfIoWehClUQ= -github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964/go.mod h1:Xd9hchkHSWYkEqJwUGisez3G1QY8Ryz0sdWrLPMGjLk= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dlclark/regexp2 v1.2.0 h1:8sAhBGEM0dRWogWqWyQeIJnxjWO6oIjl8FKqREDsGfk= -github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= -github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= -github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU= -golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= -golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200413165638-669c56c373c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0 h1:n2a8QNdAb0sZNpU9R1ALUXBbY+w51fCQDN+7EdxNBsY= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/build/utils/debug.go b/internal/build/utils/debug.go deleted file mode 100644 index 2703f31d1..000000000 --- a/internal/build/utils/debug.go +++ /dev/null @@ -1,104 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package utils - -import ( - "bufio" - "fmt" - "go/scanner" - "go/token" - "io" - "os" - "strings" -) - -// PrintSourceWithErr returns source code annotated with location of an error. -// -func PrintSourceWithErr(out io.Reader, err error) { - if IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - if e, ok := err.(scanner.ErrorList); ok { - fmt.Fprintf(os.Stderr, "\x1b[2m✖ %s\n", e.Error()) - } - fmt.Fprintln(os.Stderr, strings.Repeat("━", TerminalWidth())) - if IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - if _, ok := err.(scanner.ErrorList); ok { - cur := 0 - ferr := err.(scanner.ErrorList) - type ParseError struct { - Pos token.Position - Msg string - } - errlines := make(map[int]ParseError) - for _, e := range ferr { - errlines[e.Pos.Line] = ParseError{Pos: e.Pos, Msg: e.Msg} - } - scanner := bufio.NewScanner(out) - for scanner.Scan() { - cur++ - - if _, ok := errlines[cur]; ok { - if IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[1;31m") - } - fmt.Fprintf(os.Stderr, "%3d| ", cur) - fmt.Fprintln(os.Stderr, scanner.Text()) - } else { - if IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[2m") - } - fmt.Fprintf(os.Stderr, "%3d| ", cur) - if IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - fmt.Fprintln(os.Stderr, scanner.Text()) - } - if IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - if e, ok := errlines[cur]; ok { - if IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[31m") - } - fmt.Fprintf(os.Stderr, strings.Repeat(" ", 4)) - for i := 0; i < e.Pos.Column; i++ { - fmt.Fprintf(os.Stderr, "-") - } - fmt.Fprintf(os.Stderr, "^ ") - fmt.Fprintf(os.Stderr, e.Msg) - fmt.Fprintf(os.Stderr, "\n") - if IsTTY() { - fmt.Fprint(os.Stderr, "\x1b[0m") - } - } - } - fmt.Fprintln(os.Stderr, "") - } -} diff --git a/internal/build/utils/metadata.go b/internal/build/utils/metadata.go deleted file mode 100644 index 041926f83..000000000 --- a/internal/build/utils/metadata.go +++ /dev/null @@ -1,102 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package utils - -import ( - "fmt" - "os" - "os/exec" - "path/filepath" - "regexp" - "strings" -) - -var resVersion = regexp.MustCompile(`(\d+\.(x|\d+.\d+)).*`) - -// EsVersion returns the Elasticsearch from environment variable, Java property file, or an error. -// -func EsVersion(fpath string) (string, error) { - if envEsVersion := os.Getenv("ELASTICSEARCH_BUILD_VERSION"); envEsVersion != "" { - splitVersion := resVersion.FindStringSubmatch(envEsVersion) - return splitVersion[1], nil - } else { - return "", fmt.Errorf("ELASTICSEARCH_BUILD_VERSION is empty") - } -} - -// GitCommit returns the Git commit from environment variable or parsing information from fpath, or an error. -// -func GitCommit(fpath string) (string, error) { - if esBuildHash := os.Getenv("ELASTICSEARCH_BUILD_HASH"); esBuildHash != "" { - return esBuildHash[:7], nil - } - return "", fmt.Errorf("ELASTICSEARCH_BUILD_HASH is empty") -} - -// GitTag returns the Git tag for fpath if available, or an error. -// -func GitTag(fpath string) (string, error) { - basePath, err := basePathFromFilepath(fpath) - if err != nil { - return "", fmt.Errorf("GitCommit: %s", err) - } - - commit, err := GitCommit(fpath) - if err != nil { - return "", fmt.Errorf("GitTag: %s", err) - } - - args := strings.Split("git --git-dir="+basePath+".git tag --points-at "+commit, " ") - cmd := exec.Command(args[0:1][0], args[1:]...) - // fmt.Printf("> %s\n", strings.Join(cmd.Args, " ")) - - out, err := cmd.Output() - if err != nil { - return "", nil - } - - return strings.TrimSpace(string(out)), nil -} - -func basePathFromFilepath(fpath string) (string, error) { - var bpath strings.Builder - - fpath, err := filepath.Abs(fpath) - if err != nil { - return "", err - } - - for _, p := range strings.Split(fpath, string(filepath.Separator)) { - if p == "rest-api-spec" { - break - } - bpath.WriteString(p) - bpath.WriteRune(filepath.Separator) - } - - return bpath.String(), nil -} diff --git a/internal/build/utils/naming.go b/internal/build/utils/naming.go deleted file mode 100644 index 40d50d52a..000000000 --- a/internal/build/utils/naming.go +++ /dev/null @@ -1,125 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package utils - -import "strings" - -var ( - // Options: boolean, enum, list, number, string, time - typesToGo = map[string]string{ - "boolean": "*bool", - "enum": "string", // TODO: Custom "enum" type - "list": "[]string", - "number": "*int", - "int": "*int", - "long": "*int", - "string": "string", - "time": "time.Duration", - } -) - -// APIToGo returns the Go version of API call, eg. cluster.health => ClusterHealth -// -func APIToGo(s string) string { - ep := strings.Split(s, ".") - ns := make([]string, len(ep)) - for _, v := range ep { - m := strings.Split(v, "_") - mn := make([]string, len(m)) - for _, vv := range m { - mn = append(mn, NameToGo(vv)) - } - ns = append(ns, strings.Join(mn, "")) - } - return strings.Join(ns, "") -} - -// NameToGo returns a Go version of name, eg. node_id => NodeID. -// -func NameToGo(s string, api ...string) string { - exceptions := map[string]string{ - "index": "Index", - "id": "DocumentID", - } - - acronyms := map[string]string{ - "ip": "IP", - "id": "ID", - "ttl": "TTL", - - "api": "API", - "sql": "SQL", - "ssl": "SSL", - } - - specialMappingsForID := map[string]string{ - "DeleteScript": "ScriptID", - "GetScript": "ScriptID", - "PutScript": "ScriptID", - "IngestDeletePipeline": "PipelineID", - "IngestGetPipeline": "PipelineID", - "IngestPutPipeline": "PipelineID", - "IngestSimulate": "PipelineID", - "RenderSearchTemplate": "TemplateID", - } - - if s == "id" && api != nil && len(api) > 0 && api[0] != "" && specialMappingsForID[api[0]] != "" { - return specialMappingsForID[api[0]] - } - - if value, ok := exceptions[s]; ok { - return value - } - - ep := strings.Split(s, "_") - ns := make([]string, len(ep)) - for _, v := range ep { - if value, ok := acronyms[v]; ok { - v = value - } else if v == "uuid" { - v = "UUID" - } - ns = append(ns, strings.Title(v)) - } - return strings.Join(ns, "") -} - -// TypeToGo returns a Go version of type, eg. boolean => *bool. -// -func TypeToGo(s string, comment ...bool) string { - // If the string contains a pipe character, it's a polymorphic parameter, - // ie. it takes heterogeous values, such as "boolean" and "number" - if strings.Contains(s, "|") { - return "interface{}" - } - - if v, ok := typesToGo[s]; ok { - return v - } - - return "interface{}" -} diff --git a/internal/version/version.go b/internal/version/version.go index fb3f8c713..8c3b31425 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -27,5 +27,4 @@ package version // Client returns the client version as a string. -// const Client = "2.2.0" diff --git a/opensearch.go b/opensearch.go index ad4683e8b..b67beb381 100644 --- a/opensearch.go +++ b/opensearch.go @@ -27,8 +27,12 @@ package opensearch import ( + "bytes" + "context" + "encoding/json" "errors" "fmt" + "io" "net/http" "net/url" "os" @@ -37,36 +41,35 @@ import ( "strings" "time" - "github.com/opensearch-project/opensearch-go/v2/signer" - "github.com/opensearch-project/opensearch-go/v2/internal/version" - "github.com/opensearch-project/opensearch-go/v2/opensearchapi" "github.com/opensearch-project/opensearch-go/v2/opensearchtransport" + "github.com/opensearch-project/opensearch-go/v2/signer" ) -var ( - reVersion *regexp.Regexp -) - -func init() { - versionPattern := `^([0-9]+)\.([0-9]+)\.([0-9]+)` - reVersion = regexp.MustCompile(versionPattern) -} - const ( - defaultURL = "http://localhost:9200" - openSearch = "opensearch" - unsupportedProduct = "the client noticed that the server is not a supported distribution" - envOpenSearchURL = "OPENSEARCH_URL" - envElasticsearchURL = "ELASTICSEARCH_URL" + defaultURL = "http://localhost:9200" + openSearch = "opensearch" + unsupportedProduct = "the client noticed that the server is not a supported distribution" + envOpenSearchURL = "OPENSEARCH_URL" ) // Version returns the package version as a string. -// const Version = version.Client +// SupportedElasticVersion defines the supported major elasticsearch version +const SupportedElasticVersion = 7 + +// Error vars +var ( + ErrCreateClient = errors.New("cannot create client") + ErrCreateTransport = errors.New("error creating transport") + ErrParseVersion = errors.New("failed to parse opensearch version") + ErrParseURL = errors.New("cannot parse url") + ErrTransportMissingMethodMetrics = errors.New("transport is missing method Metrics()") + ErrTransportMissingMethodDiscoverNodes = errors.New("transport is missing method DiscoverNodes()") +) + // Config represents the client configuration. -// type Config struct { Addresses []string // A list of nodes to use. Username string // Username for HTTP Basic Authentication. @@ -105,10 +108,8 @@ type Config struct { } // Client represents the OpenSearch client. -// type Client struct { - *opensearchapi.API // Embeds the API methods - Transport opensearchtransport.Interface + Transport opensearchtransport.Interface } type esVersion struct { @@ -130,7 +131,6 @@ type info struct { // to configure the addresses; use a comma to separate multiple URLs. // // It's an error to set both OPENSEARCH_URL and ELASTICSEARCH_URL. -// func NewDefaultClient() (*Client, error) { return NewClient(Config{}) } @@ -143,15 +143,11 @@ func NewDefaultClient() (*Client, error) { // to configure the addresses; use a comma to separate multiple URLs. // // It's an error to set both OPENSEARCH_URL and ELASTICSEARCH_URL. -// func NewClient(cfg Config) (*Client, error) { var addrs []string if len(cfg.Addresses) == 0 { - envAddress, err := getAddressFromEnvironment() - if err != nil { - return nil, err - } + envAddress := getAddressFromEnvironment() addrs = envAddress } else { addrs = append(addrs, cfg.Addresses...) @@ -159,11 +155,12 @@ func NewClient(cfg Config) (*Client, error) { urls, err := addrsToURLs(addrs) if err != nil { - return nil, fmt.Errorf("cannot create client: %s", err) + return nil, fmt.Errorf("%w: %w", ErrCreateClient, err) } if len(urls) == 0 { - u, _ := url.Parse(defaultURL) // errcheck exclude + //nolint:errcheck // errcheck exclude ??? + u, _ := url.Parse(defaultURL) urls = append(urls, u) } @@ -203,98 +200,142 @@ func NewClient(cfg Config) (*Client, error) { ConnectionPoolFunc: cfg.ConnectionPoolFunc, }) if err != nil { - return nil, fmt.Errorf("error creating transport: %s", err) + return nil, fmt.Errorf("%w: %w", ErrCreateTransport, err) } client := &Client{Transport: tp} - client.API = opensearchapi.New(client) if cfg.DiscoverNodesOnStart { + //nolint:errcheck // goroutine discards return values go client.DiscoverNodes() } return client, err } -func getAddressFromEnvironment() ([]string, error) { - fromOpenSearchEnv := addrsFromEnvironment(envOpenSearchURL) - fromElasticsearchEnv := addrsFromEnvironment(envElasticsearchURL) - - if len(fromElasticsearchEnv) > 0 && len(fromOpenSearchEnv) > 0 { - return nil, fmt.Errorf("cannot create client: both %s and %s are set", envOpenSearchURL, envElasticsearchURL) - } - if len(fromOpenSearchEnv) > 0 { - return fromOpenSearchEnv, nil - } - return fromElasticsearchEnv, nil +func getAddressFromEnvironment() []string { + return addrsFromEnvironment(envOpenSearchURL) } // checkCompatibleInfo validates the information given by OpenSearch -// func checkCompatibleInfo(info info) error { major, _, _, err := ParseVersion(info.Version.Number) if err != nil { return err } + if info.Version.Distribution == openSearch { return nil } - if major != 7 { + + if major != SupportedElasticVersion { return errors.New(unsupportedProduct) } + return nil } // ParseVersion returns an int64 representation of version. -// func ParseVersion(version string) (int64, int64, int64, error) { + reVersion := regexp.MustCompile(`^([0-9]+)\.([0-9]+)\.([0-9]+)`) matches := reVersion.FindStringSubmatch(version) - + //nolint:gomnd // 4 is the minium regexp match length if len(matches) < 4 { - return 0, 0, 0, fmt.Errorf("") + return 0, 0, 0, fmt.Errorf("%w: regexp does not match on version string", ErrParseVersion) + } + + major, err := strconv.ParseInt(matches[1], 10, 0) + if err != nil { + return 0, 0, 0, fmt.Errorf("%w: %w", ErrParseVersion, err) + } + + minor, err := strconv.ParseInt(matches[2], 10, 0) + if err != nil { + return 0, 0, 0, fmt.Errorf("%w: %w", ErrParseVersion, err) + } + + patch, err := strconv.ParseInt(matches[3], 10, 0) + if err != nil { + return 0, 0, 0, fmt.Errorf("%w: %w", ErrParseVersion, err) } - major, _ := strconv.ParseInt(matches[1], 10, 0) - minor, _ := strconv.ParseInt(matches[2], 10, 0) - patch, _ := strconv.ParseInt(matches[3], 10, 0) return major, minor, patch, nil } // Perform delegates to Transport to execute a request and return a response. -// func (c *Client) Perform(req *http.Request) (*http.Response, error) { // Perform the original request. return c.Transport.Perform(req) } +// Do gets and performs the request. It also tries to parse the response into the dataPointer +func (c *Client) Do(ctx context.Context, req Request, dataPointer interface{}) (*Response, error) { + httpReq, err := req.GetRequest() + if err != nil { + return nil, err + } + + if ctx != nil { + httpReq = httpReq.WithContext(ctx) + } + + //nolint:bodyclose // body got already closed by Perform, this is a nopcloser + resp, err := c.Perform(httpReq) + if err != nil { + return nil, err + } + + response := &Response{ + StatusCode: resp.StatusCode, + Body: resp.Body, + Header: resp.Header, + } + + if dataPointer != nil && resp.Body != nil && !response.IsError() { + data, err := io.ReadAll(resp.Body) + if err != nil { + return response, fmt.Errorf("failed to read the response body, status: %d, err: %w", resp.StatusCode, err) + } + + response.Body = io.NopCloser(bytes.NewReader(data)) + + if err := json.Unmarshal(data, dataPointer); err != nil { + return response, fmt.Errorf("failed to parse body into the pointer, status: %d, body: %s, err: %w", resp.StatusCode, data, err) + } + } + + return response, nil +} + // Metrics returns the client metrics. -// func (c *Client) Metrics() (opensearchtransport.Metrics, error) { if mt, ok := c.Transport.(opensearchtransport.Measurable); ok { return mt.Metrics() } - return opensearchtransport.Metrics{}, errors.New("transport is missing method Metrics()") + + return opensearchtransport.Metrics{}, ErrTransportMissingMethodMetrics } // DiscoverNodes reloads the client connections by fetching information from the cluster. -// func (c *Client) DiscoverNodes() error { if dt, ok := c.Transport.(opensearchtransport.Discoverable); ok { return dt.DiscoverNodes() } - return errors.New("transport is missing method DiscoverNodes()") + + return ErrTransportMissingMethodDiscoverNodes } // addrsFromEnvironment returns a list of addresses by splitting // the given environment variable with comma, or an empty list. -// func addrsFromEnvironment(name string) []string { var addrs []string if envURLs, ok := os.LookupEnv(name); ok && envURLs != "" { list := strings.Split(envURLs, ",") - for _, u := range list { - addrs = append(addrs, strings.TrimSpace(u)) + addrs = make([]string, len(list)) + + for idx, u := range list { + addrs[idx] = strings.TrimSpace(u) } } @@ -302,16 +343,17 @@ func addrsFromEnvironment(name string) []string { } // addrsToURLs creates a list of url.URL structures from url list. -// func addrsToURLs(addrs []string) ([]*url.URL, error) { - var urls []*url.URL + urls := make([]*url.URL, 0) + for _, addr := range addrs { u, err := url.Parse(strings.TrimRight(addr, "/")) if err != nil { - return nil, fmt.Errorf("cannot parse url: %v", err) + return nil, fmt.Errorf("%w: %w", ErrParseURL, err) } urls = append(urls, u) } + return urls, nil } diff --git a/opensearch_benchmark_test.go b/opensearch_benchmark_test.go index 020ac38ff..e0068e89c 100644 --- a/opensearch_benchmark_test.go +++ b/opensearch_benchmark_test.go @@ -24,13 +24,14 @@ // specific language governing permissions and limitations // under the License. -// +build !integration +//go:build !integration package opensearch_test import ( "context" - "io/ioutil" + "fmt" + "io" "net/http" "strconv" "strings" @@ -40,63 +41,51 @@ import ( "github.com/opensearch-project/opensearch-go/v2/opensearchapi" ) -var defaultResponse = http.Response{ - Status: "200 OK", - StatusCode: 200, - ContentLength: 2, - Header: http.Header(map[string][]string{"Content-Type": {"application/json"}}), - Body: ioutil.NopCloser(strings.NewReader(`{}`)), -} - -var infoResponse = http.Response{ - Status: "200 OK", - StatusCode: http.StatusOK, - Header: http.Header(map[string][]string{"Content-Type": {"application/json"}}), -} - type FakeTransport struct { - InfoResponse *http.Response - FakeResponse *http.Response + Response *http.Response } -func (t *FakeTransport) RoundTrip(req *http.Request) (*http.Response, error) { - if req.URL.Path == "/" { - response := t.InfoResponse - response.Body = ioutil.NopCloser(strings.NewReader(`{ +func (t *FakeTransport) RoundTrip(_ *http.Request) (*http.Response, error) { + response := t.Response + response.Body = io.NopCloser(strings.NewReader(`{ "name" : "es1", "cluster_name" : "opensearch-go", "cluster_uuid" : "clusteruuid", "version" : { - "number" : "1.0.0", + "number" : "2.7.0", "distribution" : "opensearch", - "build_type" : "docker", - "build_hash" : "somehash", - "build_date" : "2021-06-09T06:34:20.411011746Z", - "build_snapshot" : true, - "lucene_version" : "8.9.0", - "minimum_wire_compatibility_version" : "6.8.0", - "minimum_index_compatibility_version" : "6.0.0-beta1" + "build_type" : "tar", + "build_hash" : "b7a6e09e492b1e965d827525f7863b366ef0e304", + "build_date" : "2023-04-27T21:43:09.523336706Z", + "build_snapshot" : false, + "lucene_version" : "9.5.0", + "minimum_wire_compatibility_version" : "7.10.0", + "minimum_index_compatibility_version" : "7.0.0" } }`)) - return t.InfoResponse, nil - } - return t.FakeResponse, nil + return t.Response, nil } -func newFakeTransport(b *testing.B) *FakeTransport { +func newFakeTransport(_ *testing.B, resp http.Response) *FakeTransport { return &FakeTransport{ - InfoResponse: &infoResponse, - FakeResponse: &defaultResponse, + Response: &resp, } } func BenchmarkClient(b *testing.B) { + defaultResponse := http.Response{ + Status: fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK)), + StatusCode: http.StatusOK, + ContentLength: 2, + Header: http.Header(map[string][]string{"Content-Type": {"application/json"}}), + Body: io.NopCloser(strings.NewReader(`{}`)), + } + b.ReportAllocs() b.Run("Create client with defaults", func(b *testing.B) { for i := 0; i < b.N; i++ { - _, err := opensearch.NewClient(opensearch.Config{Transport: newFakeTransport(b)}) - + _, err := opensearch.NewClient(opensearch.Config{Transport: newFakeTransport(b, defaultResponse)}) if err != nil { b.Fatalf("Unexpected error when creating a client: %s", err) } @@ -105,14 +94,24 @@ func BenchmarkClient(b *testing.B) { } func BenchmarkClientAPI(b *testing.B) { + infoResponse := http.Response{ + Status: fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK)), + StatusCode: http.StatusOK, + Header: http.Header(map[string][]string{"Content-Type": {"application/json"}}), + } + b.ReportAllocs() ctx := context.Background() - client, err := opensearch.NewClient(opensearch.Config{ - Addresses: []string{"http://localhost:9200"}, - Transport: newFakeTransport(b), - }) + client, err := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{"http://localhost:9200"}, + Transport: newFakeTransport(b, infoResponse), + }, + }, + ) if err != nil { b.Fatalf("ERROR: %s", err) } @@ -120,16 +119,14 @@ func BenchmarkClientAPI(b *testing.B) { b.Run("InfoRequest{}.Do()", func(b *testing.B) { b.ResetTimer() - req := opensearchapi.InfoRequest{} - for i := 0; i < b.N; i++ { - if _, err := req.Do(ctx, client); err != nil { + if _, err := client.Info(ctx, nil); err != nil { b.Errorf("Unexpected error when getting a response: %s", err) } } }) - b.Run("IndexRequest{...}.Do()", func(b *testing.B) { + b.Run("client.Index()", func(b *testing.B) { b.ResetTimer() var body strings.Builder @@ -141,89 +138,48 @@ func BenchmarkClientAPI(b *testing.B) { body.WriteString(docID) body.WriteString(` " }`) - req := opensearchapi.IndexRequest{ + req := opensearchapi.IndexReq{ Index: "test", DocumentID: docID, Body: strings.NewReader(body.String()), - Refresh: "true", - Pretty: true, - Timeout: 100, - } - if _, err := req.Do(ctx, client); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) + Params: opensearchapi.IndexParams{ + Refresh: "true", + Pretty: true, + Timeout: 100, + }, } - } - }) - - b.Run("Index(...)", func(b *testing.B) { - b.ResetTimer() - var body strings.Builder - - for i := 0; i < b.N; i++ { - docID := strconv.FormatInt(int64(i), 10) - body.Reset() - body.WriteString(`{"foo" : "bar `) - body.WriteString(docID) - body.WriteString(` " }`) - - _, err := client.Index( - "test", - strings.NewReader(body.String()), - client.Index.WithDocumentID(docID), - client.Index.WithRefresh("true"), - client.Index.WithPretty(), - client.Index.WithTimeout(100), - client.Index.WithContext(ctx), - ) + _, err := client.Index(ctx, req) if err != nil { b.Errorf("Unexpected error when getting a response: %s", err) } } }) - b.Run("SearchRequest{...}.Do()", func(b *testing.B) { + b.Run("client.Search()", func(b *testing.B) { b.ResetTimer() body := `{"foo" : "bar"}` - indx := []string{"test"} - for i := 0; i < b.N; i++ { - req := opensearchapi.SearchRequest{ - Index: indx, - Body: strings.NewReader(body), - Size: opensearchapi.IntPtr(25), + req := &opensearchapi.SearchReq{ + Indices: []string{"test"}, + Body: strings.NewReader(body), + Params: opensearchapi.SearchParams{ + Size: opensearchapi.ToPointer(25), Pretty: true, Timeout: 100, - } - if _, err := req.Do(ctx, client); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } + }, } - }) - - b.Run("Search(...)", func(b *testing.B) { - b.ResetTimer() - - body := `{"foo" : "bar"}` - indx := "test" for i := 0; i < b.N; i++ { - _, err := client.Search( - client.Search.WithIndex(indx), - client.Search.WithBody(strings.NewReader(body)), - client.Search.WithSize(25), - client.Search.WithPretty(), - client.Search.WithTimeout(100), - client.Search.WithContext(ctx), - ) + _, err := client.Search(ctx, req) if err != nil { b.Errorf("Unexpected error when getting a response: %s", err) } } }) - b.Run("BulkRequest{...}.Do()", func(b *testing.B) { + b.Run("client.Bulk()", func(b *testing.B) { b.ResetTimer() var body strings.Builder @@ -236,39 +192,15 @@ func BenchmarkClientAPI(b *testing.B) { body.WriteString(docID) body.WriteString(` " }`) - req := opensearchapi.BulkRequest{ - Body: strings.NewReader(body.String()), - Refresh: "true", - Pretty: true, - Timeout: 100, + req := opensearchapi.BulkReq{ + Body: strings.NewReader(body.String()), + Params: opensearchapi.BulkParams{ + Refresh: "true", + Pretty: true, + Timeout: 100, + }, } - if _, err := req.Do(ctx, client); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("Bulk(...)", func(b *testing.B) { - b.ResetTimer() - var body strings.Builder - - for i := 0; i < b.N; i++ { - docID := strconv.FormatInt(int64(i), 10) - - body.Reset() - body.WriteString(`{"index" : { "_index" : "test", "_type" : "_doc", "_id" : "` + docID + `" }}`) - body.WriteString(`{"foo" : "bar `) - body.WriteString(docID) - body.WriteString(` " }`) - - _, err := client.Bulk( - strings.NewReader(body.String()), - client.Bulk.WithRefresh("true"), - client.Bulk.WithPretty(), - client.Bulk.WithTimeout(100), - client.Bulk.WithContext(ctx), - ) - if err != nil { + if _, err := client.Bulk(ctx, req); err != nil { b.Errorf("Unexpected error when getting a response: %s", err) } } diff --git a/opensearch_example_test.go b/opensearch_example_test.go index 6c45b15d2..fbaab125e 100644 --- a/opensearch_example_test.go +++ b/opensearch_example_test.go @@ -24,11 +24,12 @@ // specific language governing permissions and limitations // under the License. -// +build !integration +//go:build !integration package opensearch_test import ( + "context" "crypto/tls" "log" "net" @@ -37,6 +38,7 @@ import ( "time" "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" "github.com/opensearch-project/opensearch-go/v2/opensearchtransport" ) @@ -45,54 +47,56 @@ func init() { } func ExampleNewDefaultClient() { - client, err := opensearch.NewDefaultClient() + ctx := context.Background() + client, err := opensearchapi.NewDefaultClient() if err != nil { log.Fatalf("Error creating the client: %s\n", err) } - res, err := client.Info() + _, err = client.Info(ctx, nil) if err != nil { log.Fatalf("Error getting the response: %s\n", err) } - defer res.Body.Close() - log.Print(client.Transport.(*opensearchtransport.Client).URLs()) + log.Print(client.Client.Transport.(*opensearchtransport.Client).URLs()) } func ExampleNewClient() { - cfg := opensearch.Config{ - Addresses: []string{ - "http://localhost:9200", - }, - Username: "foo", - Password: "bar", - Transport: &http.Transport{ - MaxIdleConnsPerHost: 10, - ResponseHeaderTimeout: time.Second, - DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, - TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS11, + cfg := opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{ + "http://localhost:9200", + }, + Username: "foo", + Password: "bar", + Transport: &http.Transport{ + MaxIdleConnsPerHost: 10, + ResponseHeaderTimeout: time.Second, + DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS12, + }, }, }, } - client, _ := opensearch.NewClient(cfg) - log.Print(client.Transport.(*opensearchtransport.Client).URLs()) + client, _ := opensearchapi.NewClient(cfg) + log.Print(client.Client.Transport.(*opensearchtransport.Client).URLs()) } func ExampleNewClient_logger() { // import "github.com/opensearch-project/opensearch-go/opensearchtransport" - // Use one of the bundled loggers: // // * opensearchtransport.TextLogger // * opensearchtransport.ColorLogger // * opensearchtransport.CurlLogger // * opensearchtransport.JSONLogger - - cfg := opensearch.Config{ - Logger: &opensearchtransport.ColorLogger{Output: os.Stdout}, + cfg := opensearchapi.Config{ + Client: opensearch.Config{ + Logger: &opensearchtransport.ColorLogger{Output: os.Stdout}, + }, } - opensearch.NewClient(cfg) + opensearchapi.NewClient(cfg) } diff --git a/opensearch_integration_test.go b/opensearch_integration_test.go index 3a438fb08..a2a479bcb 100644 --- a/opensearch_integration_test.go +++ b/opensearch_integration_test.go @@ -24,14 +24,13 @@ // specific language governing permissions and limitations // under the License. -// +build integration,!multinode +//go:build integration && !multinode package opensearch_test import ( "context" "crypto/tls" - "encoding/json" "log" "net" "net/http" @@ -47,60 +46,48 @@ import ( ) func TestClientTransport(t *testing.T) { - t.Run("Persistent", func(t *testing.T) { - client, err := opensearch.NewDefaultClient() - if err != nil { - t.Fatalf("Error creating the client: %s", err) - } - - var total int - - for i := 0; i < 101; i++ { - var curTotal int - - res, err := client.Nodes.Stats(client.Nodes.Stats.WithMetric("http")) + /* + t.Run("Persistent", func(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() if err != nil { - t.Fatalf("Unexpected error: %s", err) + t.Fatalf("Error creating the client: %s", err) } - defer res.Body.Close() - r := struct { - Nodes map[string]struct { - HTTP struct { - TotalOpened int `json:"total_opened"` - } - } - }{} + var total int - if err := json.NewDecoder(res.Body).Decode(&r); err != nil { - t.Fatalf("Error parsing the response body: %s", err) - } + for i := 0; i < 101; i++ { + var curTotal int - for _, v := range r.Nodes { - curTotal = v.HTTP.TotalOpened - break - } + res, err := client.Nodes.Stats(nil, &opensearchapi.NodesStatsReq{Metric: []string{"http"}}) + if err != nil { + t.Fatalf("Unexpected error: %s", err) + } - if curTotal < 1 { - t.Errorf("Unexpected total_opened: %d", curTotal) - } + for _, v := range res.Nodes { + curTotal = v.HTTP.TotalOpened + break + } - if total == 0 { - total = curTotal - } + if curTotal < 1 { + t.Errorf("Unexpected total_opened: %d", curTotal) + } + if total == 0 { + total = curTotal + } - if total != curTotal { - t.Errorf("Expected total_opened=%d, got: %d", total, curTotal) + if total != curTotal { + t.Errorf("Expected total_opened=%d, got: %d", total, curTotal) + } } - } - log.Printf("total_opened: %d", total) - }) + log.Printf("total_opened: %d", total) + }) + */ t.Run("Concurrent", func(t *testing.T) { var wg sync.WaitGroup - client, err := opensearch.NewDefaultClient() + client, err := opensearchapi.NewDefaultClient() if err != nil { t.Fatalf("Error creating the client: %s", err) } @@ -111,11 +98,9 @@ func TestClientTransport(t *testing.T) { go func(i int) { defer wg.Done() - res, err := client.Info() + _, err := client.Info(nil, nil) if err != nil { t.Errorf("Unexpected error: %s", err) - } else { - defer res.Body.Close() } }(i) } @@ -123,7 +108,7 @@ func TestClientTransport(t *testing.T) { }) t.Run("WithContext", func(t *testing.T) { - client, err := opensearch.NewDefaultClient() + client, err := opensearchapi.NewDefaultClient() if err != nil { t.Fatalf("Error creating the client: %s", err) } @@ -131,9 +116,8 @@ func TestClientTransport(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) defer cancel() - res, err := client.Info(client.Info.WithContext(ctx)) + _, err = client.Info(ctx, nil) if err == nil { - res.Body.Close() t.Fatal("Expected 'context deadline exceeded' error") } @@ -141,24 +125,26 @@ func TestClientTransport(t *testing.T) { }) t.Run("Configured", func(t *testing.T) { - cfg := opensearch.Config{ - Transport: &http.Transport{ - MaxIdleConnsPerHost: 10, - ResponseHeaderTimeout: time.Second, - DialContext: (&net.Dialer{Timeout: time.Nanosecond}).DialContext, - TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS11, - InsecureSkipVerify: true, + cfg := opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &http.Transport{ + MaxIdleConnsPerHost: 10, + ResponseHeaderTimeout: time.Second, + DialContext: (&net.Dialer{Timeout: time.Nanosecond}).DialContext, + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS11, + InsecureSkipVerify: true, + }, }, }, } - client, err := opensearch.NewClient(cfg) + client, err := opensearchapi.NewClient(cfg) if err != nil { t.Fatalf("Error creating the client: %s", err) } - _, err = client.Info() + _, err = client.Info(nil, nil) if err == nil { t.Fatalf("Expected error, but got: %v", err) } @@ -180,23 +166,24 @@ func (t *CustomTransport) RoundTrip(req *http.Request) (*http.Response, error) { func TestClientCustomTransport(t *testing.T) { t.Run("Customized", func(t *testing.T) { - cfg := opensearch.Config{ - Transport: &CustomTransport{ - client: http.DefaultClient, + cfg := opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &CustomTransport{ + client: http.DefaultClient, + }, }, } - client, err := opensearch.NewClient(cfg) + client, err := opensearchapi.NewClient(cfg) if err != nil { t.Fatalf("Error creating the client: %s", err) } for i := 0; i < 10; i++ { - res, err := client.Info() + _, err := client.Info(nil, nil) if err != nil { t.Fatalf("Unexpected error: %s", err) } - defer res.Body.Close() } }) @@ -208,16 +195,17 @@ func TestClientCustomTransport(t *testing.T) { Transport: http.DefaultTransport, }) - client := opensearch.Client{ - Transport: tp, API: opensearchapi.New(tp), + client := opensearchapi.Client{ + Client: &opensearch.Client{ + Transport: tp, + }, } for i := 0; i < 10; i++ { - res, err := client.Info() + _, err := client.Info(nil, nil) if err != nil { t.Fatalf("Unexpected error: %s", err) } - defer res.Body.Close() } }) } @@ -242,16 +230,17 @@ func (t *ReplacedTransport) Count() uint64 { func TestClientReplaceTransport(t *testing.T) { t.Run("Replaced", func(t *testing.T) { tr := &ReplacedTransport{} - client := opensearch.Client{ - Transport: tr, API: opensearchapi.New(tr), + client := opensearchapi.Client{ + Client: &opensearch.Client{ + Transport: tr, + }, } for i := 0; i < 10; i++ { - res, err := client.Info() + _, err := client.Info(nil, nil) if err != nil { t.Fatalf("Unexpected error: %s", err) } - defer res.Body.Close() } if tr.Count() != 10 { @@ -262,21 +251,17 @@ func TestClientReplaceTransport(t *testing.T) { func TestClientAPI(t *testing.T) { t.Run("Info", func(t *testing.T) { - client, err := opensearch.NewDefaultClient() + client, err := opensearchapi.NewDefaultClient() if err != nil { log.Fatalf("Error creating the client: %s\n", err) } - res, err := client.Info() + res, err := client.Info(nil, nil) if err != nil { log.Fatalf("Error getting the response: %s\n", err) } - defer res.Body.Close() - - var d map[string]interface{} - err = json.NewDecoder(res.Body).Decode(&d) - if err != nil { - log.Fatalf("Error parsing the response: %s\n", err) + if res.ClusterName == "" { + log.Fatalf("cluster_name is empty: %s\n", err) } }) } diff --git a/opensearch_internal_test.go b/opensearch_internal_test.go index def72f91a..a8440fcd7 100644 --- a/opensearch_internal_test.go +++ b/opensearch_internal_test.go @@ -24,13 +24,13 @@ // specific language governing permissions and limitations // under the License. -// +build !integration +//go:build !integration package opensearch import ( "errors" - "io/ioutil" + "io" "net/http" "net/url" "os" @@ -38,8 +38,6 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" - "github.com/opensearch-project/opensearch-go/v2/opensearchtransport" ) @@ -53,7 +51,7 @@ var defaultRoundTripFunc = func(req *http.Request) (*http.Response, error) { response := &http.Response{Header: http.Header{}} if req.URL.Path == "/" { - response.Body = ioutil.NopCloser(strings.NewReader(`{ + response.Body = io.NopCloser(strings.NewReader(`{ "version" : { "number" : "1.0.0", "distribution" : "opensearch" @@ -75,11 +73,8 @@ func (t *mockTransp) RoundTrip(req *http.Request) (*http.Response, error) { } func TestClientConfiguration(t *testing.T) { - t.Parallel() - t.Run("With empty", func(t *testing.T) { c, err := NewDefaultClient() - if err != nil { t.Errorf("Unexpected error: %s", err) } @@ -104,22 +99,6 @@ func TestClientConfiguration(t *testing.T) { } }) - t.Run("With URL from ELASTICSEARCH_URL", func(t *testing.T) { - os.Setenv(envElasticsearchURL, "http://elasticsearch.com") - defer func() { os.Setenv(envElasticsearchURL, "") }() - - c, err := NewClient(Config{Transport: &mockTransp{}}) - if err != nil { - t.Errorf("Unexpected error: %s", err) - } - - u := c.Transport.(*opensearchtransport.Client).URLs()[0].String() - - if u != "http://elasticsearch.com" { - t.Errorf("Unexpected URL, want=http://elasticsearch.com, got=%s", u) - } - }) - t.Run("With URL from OPENSEARCH_URL", func(t *testing.T) { os.Setenv(envOpenSearchURL, "http://opensearch.com") defer func() { os.Setenv(envOpenSearchURL, "") }() @@ -136,25 +115,9 @@ func TestClientConfiguration(t *testing.T) { } }) - t.Run("With URL from OPENSEARCH_URL and ELASTICSEARCH_URL", func(t *testing.T) { - os.Setenv(envOpenSearchURL, "http://opensearch.com") - defer func() { os.Setenv(envOpenSearchURL, "") }() - - os.Setenv(envElasticsearchURL, "http://elasticsearch.com") - defer func() { os.Setenv(envElasticsearchURL, "") }() - - _, err := NewClient(Config{Transport: &mockTransp{}}) - assert.Error(t, err, "Expected error") - - match, _ := regexp.MatchString("both .* are set", err.Error()) - if !match { - t.Errorf("Expected error when addresses from OPENSEARCH_URL and ELASTICSEARCH_URL are used together, got: %v", err) - } - }) - t.Run("With URL from environment and cfg.Addresses", func(t *testing.T) { - os.Setenv(envElasticsearchURL, "http://example.com") - defer func() { os.Setenv(envElasticsearchURL, "") }() + os.Setenv(envOpenSearchURL, "http://example.com") + defer func() { os.Setenv(envOpenSearchURL, "") }() c, err := NewClient(Config{Addresses: []string{"http://localhost:8080//"}, Transport: &mockTransp{}}) if err != nil { @@ -178,8 +141,8 @@ func TestClientConfiguration(t *testing.T) { }) t.Run("With invalid URL from environment", func(t *testing.T) { - os.Setenv(envElasticsearchURL, ":foobar") - defer func() { os.Setenv(envElasticsearchURL, "") }() + os.Setenv(envOpenSearchURL, ":foobar") + defer func() { os.Setenv(envOpenSearchURL, "") }() c, err := NewDefaultClient() if err == nil { @@ -194,7 +157,7 @@ func TestClientConfiguration(t *testing.T) { RoundTripFunc: func(request *http.Request) (*http.Response, error) { return &http.Response{ Header: http.Header{}, - Body: ioutil.NopCloser(strings.NewReader("")), + Body: io.NopCloser(strings.NewReader("")), }, nil }, }, @@ -208,18 +171,20 @@ func TestClientConfiguration(t *testing.T) { func TestClientInterface(t *testing.T) { t.Run("Transport", func(t *testing.T) { c, err := NewClient(Config{Transport: &mockTransp{}}) - if err != nil { t.Fatalf("Unexpected error: %s", err) } - if called != false { // megacheck ignore + if called != false { t.Errorf("Unexpected call to transport by client") } - c.Perform(&http.Request{URL: &url.URL{}, Header: make(http.Header)}) // errcheck ignore + res, err := c.Perform(&http.Request{URL: &url.URL{}, Header: make(http.Header)}) // errcheck ignore + if err == nil && res != nil && res.Body != nil { + res.Body.Close() + } - if called != true { // megacheck ignore + if called != true { t.Errorf("Expected client to call transport") } }) @@ -438,7 +403,7 @@ func TestGenuineCheckInfo(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if err := checkCompatibleInfo(tt.info); (err != nil) != tt.wantErr && err != tt.err { + if err := checkCompatibleInfo(tt.info); (err != nil) != tt.wantErr && !errors.Is(err, tt.err) { t.Errorf("checkCompatibleInfo() error = %v, wantErr %v", err, tt.wantErr) } }) diff --git a/opensearch_secure_integration_test.go b/opensearch_secure_integration_test.go index 3e0816a37..1ee91da44 100644 --- a/opensearch_secure_integration_test.go +++ b/opensearch_secure_integration_test.go @@ -7,31 +7,48 @@ // Modifications Copyright OpenSearch Contributors. See // GitHub history for details. -// +build integration,secure +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build integration && secure package opensearch_test import ( + "context" "crypto/tls" - "encoding/json" "log" "net/http" "testing" - "github.com/opensearch-project/opensearch-go/v2" "github.com/stretchr/testify/assert" -) -func getSecuredClient() (*opensearch.Client, error) { + "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) - return opensearch.NewClient(opensearch.Config{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, +func getSecuredClient() (*opensearchapi.Client, error) { + return opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Username: "admin", + Password: "admin", + Addresses: []string{"https://localhost:9200"}, + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + }, + }, }, - Addresses: []string{"https://localhost:9200"}, - Username: "admin", - Password: "admin", - }) + ) } type clusterVersion struct { @@ -47,24 +64,18 @@ type Info struct { func TestSecuredClientAPI(t *testing.T) { t.Run("Check Info", func(t *testing.T) { + ctx := context.Background() client, err := getSecuredClient() if err != nil { log.Fatalf("Error creating the client: %s\n", err) } - res, err := client.Info() + res, err := client.Info(ctx, nil) if err != nil { log.Fatalf("Error getting the response: %s\n", err) } - defer res.Body.Close() - var infoResponse Info - err = json.NewDecoder(res.Body).Decode(&infoResponse) - if err != nil { - log.Fatalf("Error parsing the response: %s\n", err) - } - assert.True(t, len(infoResponse.Version.Number) > 0, "version number should not be empty") - assert.True(t, len(infoResponse.Tagline) > 0, "tagline should not be empty") - assert.True(t, len(infoResponse.Version.Distribution) > 0 || len(infoResponse.Version.BuildFlavor) > 0, - "Either distribution or build flavor should not be empty") + assert.True(t, len(res.Version.Number) > 0, "version number should not be empty") + assert.True(t, len(res.Tagline) > 0, "tagline should not be empty") + assert.True(t, len(res.Version.Distribution) > 0, "distribution should not be empty") }) } diff --git a/opensearchapi/api._.go b/opensearchapi/api._.go deleted file mode 100755 index 961aa212a..000000000 --- a/opensearchapi/api._.go +++ /dev/null @@ -1,412 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -// API contains the OpenSearch APIs -type API struct { - Cat *Cat - Cluster *Cluster - Indices *Indices - Ingest *Ingest - Nodes *Nodes - Remote *Remote - Snapshot *Snapshot - Tasks *Tasks - PointInTime *PointInTime - - Bulk Bulk - ClearScroll ClearScroll - Count Count - Create Create - DanglingIndicesDeleteDanglingIndex DanglingIndicesDeleteDanglingIndex - DanglingIndicesImportDanglingIndex DanglingIndicesImportDanglingIndex - DanglingIndicesListDanglingIndices DanglingIndicesListDanglingIndices - DeleteByQuery DeleteByQuery - DeleteByQueryRethrottle DeleteByQueryRethrottle - Delete Delete - DeleteScript DeleteScript - Exists Exists - ExistsSource ExistsSource - Explain Explain - FieldCaps FieldCaps - Get Get - GetScriptContext GetScriptContext - GetScriptLanguages GetScriptLanguages - GetScript GetScript - GetSource GetSource - Index Index - Info Info - Mget Mget - Msearch Msearch - MsearchTemplate MsearchTemplate - Mtermvectors Mtermvectors - Ping Ping - PutScript PutScript - RankEval RankEval - Reindex Reindex - ReindexRethrottle ReindexRethrottle - RenderSearchTemplate RenderSearchTemplate - ScriptsPainlessExecute ScriptsPainlessExecute - Scroll Scroll - Search Search - SearchShards SearchShards - SearchTemplate SearchTemplate - TermsEnum TermsEnum - Termvectors Termvectors - UpdateByQuery UpdateByQuery - UpdateByQueryRethrottle UpdateByQueryRethrottle - Update Update -} - -// Cat contains the Cat APIs -type Cat struct { - Aliases CatAliases - Allocation CatAllocation - ClusterManager CatClusterManager - Count CatCount - Fielddata CatFielddata - Health CatHealth - Help CatHelp - Indices CatIndices - Nodeattrs CatNodeattrs - Nodes CatNodes - PendingTasks CatPendingTasks - Plugins CatPlugins - Recovery CatRecovery - Repositories CatRepositories - Segments CatSegments - Shards CatShards - Snapshots CatSnapshots - Tasks CatTasks - Templates CatTemplates - ThreadPool CatThreadPool - - // Deprecated: To promote inclusive language, please use ClusterManager instead. - Master CatMaster -} - -// Cluster contains the Cluster APIs -type Cluster struct { - AllocationExplain ClusterAllocationExplain - DeleteComponentTemplate ClusterDeleteComponentTemplate - DeleteVotingConfigExclusions ClusterDeleteVotingConfigExclusions - ExistsComponentTemplate ClusterExistsComponentTemplate - GetComponentTemplate ClusterGetComponentTemplate - GetSettings ClusterGetSettings - Health ClusterHealth - PendingTasks ClusterPendingTasks - PostVotingConfigExclusions ClusterPostVotingConfigExclusions - PutComponentTemplate ClusterPutComponentTemplate - PutSettings ClusterPutSettings - RemoteInfo ClusterRemoteInfo - Reroute ClusterReroute - State ClusterState - Stats ClusterStats -} - -// Indices contains the Indices APIs -type Indices struct { - AddBlock IndicesAddBlock - Analyze IndicesAnalyze - ClearCache IndicesClearCache - Clone IndicesClone - Close IndicesClose - Create IndicesCreate - CreateDataStream IndicesCreateDataStream - DeleteAlias IndicesDeleteAlias - DeleteIndexTemplate IndicesDeleteIndexTemplate - Delete IndicesDelete - DeleteTemplate IndicesDeleteTemplate - DeleteDataStream IndicesDeleteDataStream - DiskUsage IndicesDiskUsage - ExistsAlias IndicesExistsAlias - ExistsIndexTemplate IndicesExistsIndexTemplate - Exists IndicesExists - ExistsTemplate IndicesExistsTemplate - FieldUsageStats IndicesFieldUsageStats - Flush IndicesFlush - Forcemerge IndicesForcemerge - GetAlias IndicesGetAlias - GetFieldMapping IndicesGetFieldMapping - GetIndexTemplate IndicesGetIndexTemplate - GetMapping IndicesGetMapping - Get IndicesGet - GetSettings IndicesGetSettings - GetTemplate IndicesGetTemplate - GetDataStream IndicesGetDataStream - GetDataStreamStats IndicesGetDataStreamStats - GetUpgrade IndicesGetUpgrade - Open IndicesOpen - PutAlias IndicesPutAlias - PutIndexTemplate IndicesPutIndexTemplate - PutMapping IndicesPutMapping - PutSettings IndicesPutSettings - PutTemplate IndicesPutTemplate - Recovery IndicesRecovery - Refresh IndicesRefresh - ResolveIndex IndicesResolveIndex - Rollover IndicesRollover - Segments IndicesSegments - ShardStores IndicesShardStores - Shrink IndicesShrink - SimulateIndexTemplate IndicesSimulateIndexTemplate - SimulateTemplate IndicesSimulateTemplate - Split IndicesSplit - Stats IndicesStats - UpdateAliases IndicesUpdateAliases - Upgrade IndicesUpgrade - ValidateQuery IndicesValidateQuery -} - -// Ingest contains the Ingest APIs -type Ingest struct { - DeletePipeline IngestDeletePipeline - GetPipeline IngestGetPipeline - ProcessorGrok IngestProcessorGrok - PutPipeline IngestPutPipeline - Simulate IngestSimulate -} - -// Nodes contains the Nodes APIs -type Nodes struct { - HotThreads NodesHotThreads - Info NodesInfo - ReloadSecureSettings NodesReloadSecureSettings - Stats NodesStats - Usage NodesUsage -} - -// Remote contains the Remote APIs -type Remote struct { -} - -// Snapshot contains the Snapshot APIs -type Snapshot struct { - CleanupRepository SnapshotCleanupRepository - Clone SnapshotClone - CreateRepository SnapshotCreateRepository - Create SnapshotCreate - DeleteRepository SnapshotDeleteRepository - Delete SnapshotDelete - GetRepository SnapshotGetRepository - Get SnapshotGet - Restore SnapshotRestore - Status SnapshotStatus - VerifyRepository SnapshotVerifyRepository -} - -// Tasks contains the Tasks APIs -type Tasks struct { - Cancel TasksCancel - Get TasksGet - List TasksList -} - -// PointInTime contains the Point In Time APIs -type PointInTime struct { - Create PointInTimeCreate - Delete PointInTimeDelete - Get PointInTimeGet -} - -// New creates new API -func New(t Transport) *API { - return &API{ - Bulk: newBulkFunc(t), - ClearScroll: newClearScrollFunc(t), - Count: newCountFunc(t), - Create: newCreateFunc(t), - DanglingIndicesDeleteDanglingIndex: newDanglingIndicesDeleteDanglingIndexFunc(t), - DanglingIndicesImportDanglingIndex: newDanglingIndicesImportDanglingIndexFunc(t), - DanglingIndicesListDanglingIndices: newDanglingIndicesListDanglingIndicesFunc(t), - DeleteByQuery: newDeleteByQueryFunc(t), - DeleteByQueryRethrottle: newDeleteByQueryRethrottleFunc(t), - Delete: newDeleteFunc(t), - DeleteScript: newDeleteScriptFunc(t), - Exists: newExistsFunc(t), - ExistsSource: newExistsSourceFunc(t), - Explain: newExplainFunc(t), - FieldCaps: newFieldCapsFunc(t), - Get: newGetFunc(t), - GetScriptContext: newGetScriptContextFunc(t), - GetScriptLanguages: newGetScriptLanguagesFunc(t), - GetScript: newGetScriptFunc(t), - GetSource: newGetSourceFunc(t), - Index: newIndexFunc(t), - Info: newInfoFunc(t), - Mget: newMgetFunc(t), - Msearch: newMsearchFunc(t), - MsearchTemplate: newMsearchTemplateFunc(t), - Mtermvectors: newMtermvectorsFunc(t), - Ping: newPingFunc(t), - PutScript: newPutScriptFunc(t), - RankEval: newRankEvalFunc(t), - Reindex: newReindexFunc(t), - ReindexRethrottle: newReindexRethrottleFunc(t), - RenderSearchTemplate: newRenderSearchTemplateFunc(t), - ScriptsPainlessExecute: newScriptsPainlessExecuteFunc(t), - Scroll: newScrollFunc(t), - Search: newSearchFunc(t), - SearchShards: newSearchShardsFunc(t), - SearchTemplate: newSearchTemplateFunc(t), - TermsEnum: newTermsEnumFunc(t), - Termvectors: newTermvectorsFunc(t), - UpdateByQuery: newUpdateByQueryFunc(t), - UpdateByQueryRethrottle: newUpdateByQueryRethrottleFunc(t), - Update: newUpdateFunc(t), - Cat: &Cat{ - Aliases: newCatAliasesFunc(t), - Allocation: newCatAllocationFunc(t), - ClusterManager: newCatClusterManagerFunc(t), - Count: newCatCountFunc(t), - Fielddata: newCatFielddataFunc(t), - Health: newCatHealthFunc(t), - Help: newCatHelpFunc(t), - Indices: newCatIndicesFunc(t), - Master: newCatMasterFunc(t), - Nodeattrs: newCatNodeattrsFunc(t), - Nodes: newCatNodesFunc(t), - PendingTasks: newCatPendingTasksFunc(t), - Plugins: newCatPluginsFunc(t), - Recovery: newCatRecoveryFunc(t), - Repositories: newCatRepositoriesFunc(t), - Segments: newCatSegmentsFunc(t), - Shards: newCatShardsFunc(t), - Snapshots: newCatSnapshotsFunc(t), - Tasks: newCatTasksFunc(t), - Templates: newCatTemplatesFunc(t), - ThreadPool: newCatThreadPoolFunc(t), - }, - Cluster: &Cluster{ - AllocationExplain: newClusterAllocationExplainFunc(t), - DeleteComponentTemplate: newClusterDeleteComponentTemplateFunc(t), - DeleteVotingConfigExclusions: newClusterDeleteVotingConfigExclusionsFunc(t), - ExistsComponentTemplate: newClusterExistsComponentTemplateFunc(t), - GetComponentTemplate: newClusterGetComponentTemplateFunc(t), - GetSettings: newClusterGetSettingsFunc(t), - Health: newClusterHealthFunc(t), - PendingTasks: newClusterPendingTasksFunc(t), - PostVotingConfigExclusions: newClusterPostVotingConfigExclusionsFunc(t), - PutComponentTemplate: newClusterPutComponentTemplateFunc(t), - PutSettings: newClusterPutSettingsFunc(t), - RemoteInfo: newClusterRemoteInfoFunc(t), - Reroute: newClusterRerouteFunc(t), - State: newClusterStateFunc(t), - Stats: newClusterStatsFunc(t), - }, - Indices: &Indices{ - AddBlock: newIndicesAddBlockFunc(t), - Analyze: newIndicesAnalyzeFunc(t), - ClearCache: newIndicesClearCacheFunc(t), - Clone: newIndicesCloneFunc(t), - Close: newIndicesCloseFunc(t), - Create: newIndicesCreateFunc(t), - CreateDataStream: newIndicesCreateDataStreamFunc(t), - DeleteAlias: newIndicesDeleteAliasFunc(t), - DeleteIndexTemplate: newIndicesDeleteIndexTemplateFunc(t), - Delete: newIndicesDeleteFunc(t), - DeleteTemplate: newIndicesDeleteTemplateFunc(t), - DeleteDataStream: newIndicesDeleteDataStreamFunc(t), - DiskUsage: newIndicesDiskUsageFunc(t), - ExistsAlias: newIndicesExistsAliasFunc(t), - ExistsIndexTemplate: newIndicesExistsIndexTemplateFunc(t), - Exists: newIndicesExistsFunc(t), - ExistsTemplate: newIndicesExistsTemplateFunc(t), - FieldUsageStats: newIndicesFieldUsageStatsFunc(t), - Flush: newIndicesFlushFunc(t), - Forcemerge: newIndicesForcemergeFunc(t), - GetAlias: newIndicesGetAliasFunc(t), - GetFieldMapping: newIndicesGetFieldMappingFunc(t), - GetIndexTemplate: newIndicesGetIndexTemplateFunc(t), - GetMapping: newIndicesGetMappingFunc(t), - Get: newIndicesGetFunc(t), - GetSettings: newIndicesGetSettingsFunc(t), - GetTemplate: newIndicesGetTemplateFunc(t), - GetDataStream: newIndicesGetDataStreamFunc(t), - GetDataStreamStats: newIndicesGetDataStreamStatsFunc(t), - GetUpgrade: newIndicesGetUpgradeFunc(t), - Open: newIndicesOpenFunc(t), - PutAlias: newIndicesPutAliasFunc(t), - PutIndexTemplate: newIndicesPutIndexTemplateFunc(t), - PutMapping: newIndicesPutMappingFunc(t), - PutSettings: newIndicesPutSettingsFunc(t), - PutTemplate: newIndicesPutTemplateFunc(t), - Recovery: newIndicesRecoveryFunc(t), - Refresh: newIndicesRefreshFunc(t), - ResolveIndex: newIndicesResolveIndexFunc(t), - Rollover: newIndicesRolloverFunc(t), - Segments: newIndicesSegmentsFunc(t), - ShardStores: newIndicesShardStoresFunc(t), - Shrink: newIndicesShrinkFunc(t), - SimulateIndexTemplate: newIndicesSimulateIndexTemplateFunc(t), - SimulateTemplate: newIndicesSimulateTemplateFunc(t), - Split: newIndicesSplitFunc(t), - Stats: newIndicesStatsFunc(t), - UpdateAliases: newIndicesUpdateAliasesFunc(t), - Upgrade: newIndicesUpgradeFunc(t), - ValidateQuery: newIndicesValidateQueryFunc(t), - }, - Ingest: &Ingest{ - DeletePipeline: newIngestDeletePipelineFunc(t), - GetPipeline: newIngestGetPipelineFunc(t), - ProcessorGrok: newIngestProcessorGrokFunc(t), - PutPipeline: newIngestPutPipelineFunc(t), - Simulate: newIngestSimulateFunc(t), - }, - Nodes: &Nodes{ - HotThreads: newNodesHotThreadsFunc(t), - Info: newNodesInfoFunc(t), - ReloadSecureSettings: newNodesReloadSecureSettingsFunc(t), - Stats: newNodesStatsFunc(t), - Usage: newNodesUsageFunc(t), - }, - Remote: &Remote{}, - Snapshot: &Snapshot{ - CleanupRepository: newSnapshotCleanupRepositoryFunc(t), - Clone: newSnapshotCloneFunc(t), - CreateRepository: newSnapshotCreateRepositoryFunc(t), - Create: newSnapshotCreateFunc(t), - DeleteRepository: newSnapshotDeleteRepositoryFunc(t), - Delete: newSnapshotDeleteFunc(t), - GetRepository: newSnapshotGetRepositoryFunc(t), - Get: newSnapshotGetFunc(t), - Restore: newSnapshotRestoreFunc(t), - Status: newSnapshotStatusFunc(t), - VerifyRepository: newSnapshotVerifyRepositoryFunc(t), - }, - Tasks: &Tasks{ - Cancel: newTasksCancelFunc(t), - Get: newTasksGetFunc(t), - List: newTasksListFunc(t), - }, - PointInTime: &PointInTime{ - Create: newPointInTimeCreateFunc(t), - Delete: newPointInTimeDeleteFunc(t), - Get: newPointInTimeGetFunc(t), - }, - } -} diff --git a/opensearchapi/api.bulk.go b/opensearchapi/api.bulk.go deleted file mode 100644 index b19db6a21..000000000 --- a/opensearchapi/api.bulk.go +++ /dev/null @@ -1,348 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newBulkFunc(t Transport) Bulk { - return func(body io.Reader, o ...func(*BulkRequest)) (*Response, error) { - var r = BulkRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Bulk allows to perform multiple index/update/delete operations in a single request. -// -// -type Bulk func(body io.Reader, o ...func(*BulkRequest)) (*Response, error) - -// BulkRequest configures the Bulk API request. -// -type BulkRequest struct { - Index string - - Body io.Reader - - Pipeline string - Refresh string - RequireAlias *bool - Routing string - Source interface{} - SourceExcludes []string - SourceIncludes []string - Timeout time.Duration - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r BulkRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(r.Index) + 1 + len("_bulk")) - if r.Index != "" { - path.WriteString("/") - path.WriteString(r.Index) - } - path.WriteString("/") - path.WriteString("_bulk") - - params = make(map[string]string) - - if r.Pipeline != "" { - params["pipeline"] = r.Pipeline - } - - if r.Refresh != "" { - params["refresh"] = r.Refresh - } - - if r.RequireAlias != nil { - params["require_alias"] = strconv.FormatBool(*r.RequireAlias) - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if source, ok := r.Source.(bool); ok { - params["_source"] = strconv.FormatBool(source) - } else if source, ok := r.Source.(string); ok && source != "" { - params["_source"] = source - } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { - params["_source"] = strings.Join(sources, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Bulk) WithContext(v context.Context) func(*BulkRequest) { - return func(r *BulkRequest) { - r.ctx = v - } -} - -// WithIndex - default index for items which don't provide one. -// -func (f Bulk) WithIndex(v string) func(*BulkRequest) { - return func(r *BulkRequest) { - r.Index = v - } -} - -// WithPipeline - the pipeline ID to preprocess incoming documents with. -// -func (f Bulk) WithPipeline(v string) func(*BulkRequest) { - return func(r *BulkRequest) { - r.Pipeline = v - } -} - -// WithRefresh - if `true` then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes.. -// -func (f Bulk) WithRefresh(v string) func(*BulkRequest) { - return func(r *BulkRequest) { - r.Refresh = v - } -} - -// WithRequireAlias - sets require_alias for all incoming documents. defaults to unset (false). -// -func (f Bulk) WithRequireAlias(v bool) func(*BulkRequest) { - return func(r *BulkRequest) { - r.RequireAlias = &v - } -} - -// WithRouting - specific routing value. -// -func (f Bulk) WithRouting(v string) func(*BulkRequest) { - return func(r *BulkRequest) { - r.Routing = v - } -} - -// WithSource - true or false to return the _source field or not, or default list of fields to return, can be overridden on each sub-request. -// -func (f Bulk) WithSource(v interface{}) func(*BulkRequest) { - return func(r *BulkRequest) { - r.Source = v - } -} - -// WithSourceExcludes - default list of fields to exclude from the returned _source field, can be overridden on each sub-request. -// -func (f Bulk) WithSourceExcludes(v ...string) func(*BulkRequest) { - return func(r *BulkRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - default list of fields to extract and return from the _source field, can be overridden on each sub-request. -// -func (f Bulk) WithSourceIncludes(v ...string) func(*BulkRequest) { - return func(r *BulkRequest) { - r.SourceIncludes = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f Bulk) WithTimeout(v time.Duration) func(*BulkRequest) { - return func(r *BulkRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the bulk operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1). -// -func (f Bulk) WithWaitForActiveShards(v string) func(*BulkRequest) { - return func(r *BulkRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Bulk) WithPretty() func(*BulkRequest) { - return func(r *BulkRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Bulk) WithHuman() func(*BulkRequest) { - return func(r *BulkRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Bulk) WithErrorTrace() func(*BulkRequest) { - return func(r *BulkRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Bulk) WithFilterPath(v ...string) func(*BulkRequest) { - return func(r *BulkRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Bulk) WithHeader(h map[string]string) func(*BulkRequest) { - return func(r *BulkRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Bulk) WithOpaqueID(s string) func(*BulkRequest) { - return func(r *BulkRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.aliases.go b/opensearchapi/api.cat.aliases.go deleted file mode 100644 index 608a13c2a..000000000 --- a/opensearchapi/api.cat.aliases.go +++ /dev/null @@ -1,312 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newCatAliasesFunc(t Transport) CatAliases { - return func(o ...func(*CatAliasesRequest)) (*Response, error) { - var r = CatAliasesRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatAliases shows information about currently configured aliases to indices including filter and routing infos. -// -// -type CatAliases func(o ...func(*CatAliasesRequest)) (*Response, error) - -// CatAliasesRequest configures the Cat Aliases API request. -// -type CatAliasesRequest struct { - Name []string - - ExpandWildcards string - Format string - H []string - Help *bool - Local *bool - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatAliasesRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("aliases") + 1 + len(strings.Join(r.Name, ","))) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("aliases") - if len(r.Name) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Name, ",")) - } - - params = make(map[string]string) - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatAliases) WithContext(v context.Context) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.ctx = v - } -} - -// WithName - a list of alias names to return. -// -func (f CatAliases) WithName(v ...string) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.Name = v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f CatAliases) WithExpandWildcards(v string) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.ExpandWildcards = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatAliases) WithFormat(v string) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatAliases) WithH(v ...string) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatAliases) WithHelp(v bool) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.Help = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f CatAliases) WithLocal(v bool) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.Local = &v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatAliases) WithS(v ...string) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatAliases) WithV(v bool) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatAliases) WithPretty() func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatAliases) WithHuman() func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatAliases) WithErrorTrace() func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatAliases) WithFilterPath(v ...string) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatAliases) WithHeader(h map[string]string) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatAliases) WithOpaqueID(s string) func(*CatAliasesRequest) { - return func(r *CatAliasesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.allocation.go b/opensearchapi/api.cat.allocation.go deleted file mode 100644 index ff76b99c3..000000000 --- a/opensearchapi/api.cat.allocation.go +++ /dev/null @@ -1,342 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatAllocationFunc(t Transport) CatAllocation { - return func(o ...func(*CatAllocationRequest)) (*Response, error) { - var r = CatAllocationRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatAllocation provides a snapshot of how many shards are allocated to each data node and how much disk space they are using. -// -// -type CatAllocation func(o ...func(*CatAllocationRequest)) (*Response, error) - -// CatAllocationRequest configures the Cat Allocation API request. -// -type CatAllocationRequest struct { - NodeID []string - - Bytes string - Format string - H []string - Help *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatAllocationRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("allocation") + 1 + len(strings.Join(r.NodeID, ","))) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("allocation") - if len(r.NodeID) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.NodeID, ",")) - } - - params = make(map[string]string) - - if r.Bytes != "" { - params["bytes"] = r.Bytes - } - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatAllocation) WithContext(v context.Context) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.ctx = v - } -} - -// WithNodeID - a list of node ids or names to limit the returned information. -// -func (f CatAllocation) WithNodeID(v ...string) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.NodeID = v - } -} - -// WithBytes - the unit in which to display byte values. -// -func (f CatAllocation) WithBytes(v string) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.Bytes = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatAllocation) WithFormat(v string) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatAllocation) WithH(v ...string) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatAllocation) WithHelp(v bool) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.Help = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f CatAllocation) WithLocal(v bool) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatAllocation) WithMasterTimeout(v time.Duration) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatAllocation) WithClusterManagerTimeout(v time.Duration) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatAllocation) WithS(v ...string) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatAllocation) WithV(v bool) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatAllocation) WithPretty() func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatAllocation) WithHuman() func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatAllocation) WithErrorTrace() func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatAllocation) WithFilterPath(v ...string) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatAllocation) WithHeader(h map[string]string) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatAllocation) WithOpaqueID(s string) func(*CatAllocationRequest) { - return func(r *CatAllocationRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.cluster_manager.go b/opensearchapi/api.cat.cluster_manager.go deleted file mode 100644 index 1483478de..000000000 --- a/opensearchapi/api.cat.cluster_manager.go +++ /dev/null @@ -1,275 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatClusterManagerFunc(t Transport) CatClusterManager { - return func(o ...func(*CatClusterManagerRequest)) (*Response, error) { - var r = CatClusterManagerRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatClusterManager returns information about the cluster-manager node. -type CatClusterManager func(o ...func(*CatClusterManagerRequest)) (*Response, error) - -// CatClusterManagerRequest configures the Cat Cluster Manager API request. -type CatClusterManagerRequest struct { - Format string - H []string - Help *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -func (r CatClusterManagerRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cat/cluster_manager")) - path.WriteString("/_cat/cluster_manager") - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -func (f CatClusterManager) WithContext(v context.Context) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.ctx = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -func (f CatClusterManager) WithFormat(v string) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -func (f CatClusterManager) WithH(v ...string) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.H = v - } -} - -// WithHelp - return help information. -func (f CatClusterManager) WithHelp(v bool) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.Help = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -func (f CatClusterManager) WithLocal(v bool) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -func (f CatClusterManager) WithMasterTimeout(v time.Duration) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -func (f CatClusterManager) WithClusterManagerTimeout(v time.Duration) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -func (f CatClusterManager) WithS(v ...string) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -func (f CatClusterManager) WithV(v bool) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -func (f CatClusterManager) WithPretty() func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -func (f CatClusterManager) WithHuman() func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -func (f CatClusterManager) WithErrorTrace() func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -func (f CatClusterManager) WithFilterPath(v ...string) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -func (f CatClusterManager) WithHeader(h map[string]string) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -func (f CatClusterManager) WithOpaqueID(s string) func(*CatClusterManagerRequest) { - return func(r *CatClusterManagerRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.count.go b/opensearchapi/api.cat.count.go deleted file mode 100644 index 1991e0d3b..000000000 --- a/opensearchapi/api.cat.count.go +++ /dev/null @@ -1,287 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newCatCountFunc(t Transport) CatCount { - return func(o ...func(*CatCountRequest)) (*Response, error) { - var r = CatCountRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatCount provides quick access to the document count of the entire cluster, or individual indices. -// -// -type CatCount func(o ...func(*CatCountRequest)) (*Response, error) - -// CatCountRequest configures the Cat Count API request. -// -type CatCountRequest struct { - Index []string - - Format string - H []string - Help *bool - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatCountRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("count") + 1 + len(strings.Join(r.Index, ","))) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("count") - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatCount) WithContext(v context.Context) func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to limit the returned information. -// -func (f CatCount) WithIndex(v ...string) func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.Index = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatCount) WithFormat(v string) func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatCount) WithH(v ...string) func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatCount) WithHelp(v bool) func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.Help = &v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatCount) WithS(v ...string) func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatCount) WithV(v bool) func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatCount) WithPretty() func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatCount) WithHuman() func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatCount) WithErrorTrace() func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatCount) WithFilterPath(v ...string) func(*CatCountRequest) { - return func(r *CatCountRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatCount) WithHeader(h map[string]string) func(*CatCountRequest) { - return func(r *CatCountRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatCount) WithOpaqueID(s string) func(*CatCountRequest) { - return func(r *CatCountRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.fielddata.go b/opensearchapi/api.cat.fielddata.go deleted file mode 100644 index 897512efd..000000000 --- a/opensearchapi/api.cat.fielddata.go +++ /dev/null @@ -1,304 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newCatFielddataFunc(t Transport) CatFielddata { - return func(o ...func(*CatFielddataRequest)) (*Response, error) { - var r = CatFielddataRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatFielddata shows how much heap memory is currently being used by fielddata on every data node in the cluster. -// -// -type CatFielddata func(o ...func(*CatFielddataRequest)) (*Response, error) - -// CatFielddataRequest configures the Cat Fielddata API request. -// -type CatFielddataRequest struct { - Fields []string - - Bytes string - Format string - H []string - Help *bool - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatFielddataRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("fielddata") + 1 + len(strings.Join(r.Fields, ","))) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("fielddata") - if len(r.Fields) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Fields, ",")) - } - - params = make(map[string]string) - - if r.Bytes != "" { - params["bytes"] = r.Bytes - } - - if len(r.Fields) > 0 { - params["fields"] = strings.Join(r.Fields, ",") - } - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatFielddata) WithContext(v context.Context) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.ctx = v - } -} - -// WithFields - a list of fields to return the fielddata size. -// -func (f CatFielddata) WithFields(v ...string) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.Fields = v - } -} - -// WithBytes - the unit in which to display byte values. -// -func (f CatFielddata) WithBytes(v string) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.Bytes = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatFielddata) WithFormat(v string) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatFielddata) WithH(v ...string) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatFielddata) WithHelp(v bool) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.Help = &v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatFielddata) WithS(v ...string) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatFielddata) WithV(v bool) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatFielddata) WithPretty() func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatFielddata) WithHuman() func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatFielddata) WithErrorTrace() func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatFielddata) WithFilterPath(v ...string) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatFielddata) WithHeader(h map[string]string) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatFielddata) WithOpaqueID(s string) func(*CatFielddataRequest) { - return func(r *CatFielddataRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.health.go b/opensearchapi/api.cat.health.go deleted file mode 100644 index cadbe6750..000000000 --- a/opensearchapi/api.cat.health.go +++ /dev/null @@ -1,296 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newCatHealthFunc(t Transport) CatHealth { - return func(o ...func(*CatHealthRequest)) (*Response, error) { - var r = CatHealthRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatHealth returns a concise representation of the cluster health. -// -// -type CatHealth func(o ...func(*CatHealthRequest)) (*Response, error) - -// CatHealthRequest configures the Cat Health API request. -// -type CatHealthRequest struct { - Format string - H []string - Help *bool - S []string - Time string - Ts *bool - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatHealthRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cat/health")) - path.WriteString("/_cat/health") - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.Time != "" { - params["time"] = r.Time - } - - if r.Ts != nil { - params["ts"] = strconv.FormatBool(*r.Ts) - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatHealth) WithContext(v context.Context) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.ctx = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatHealth) WithFormat(v string) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatHealth) WithH(v ...string) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatHealth) WithHelp(v bool) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.Help = &v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatHealth) WithS(v ...string) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.S = v - } -} - -// WithTime - the unit in which to display time values. -// -func (f CatHealth) WithTime(v string) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.Time = v - } -} - -// WithTs - set to false to disable timestamping. -// -func (f CatHealth) WithTs(v bool) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.Ts = &v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatHealth) WithV(v bool) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatHealth) WithPretty() func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatHealth) WithHuman() func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatHealth) WithErrorTrace() func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatHealth) WithFilterPath(v ...string) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatHealth) WithHeader(h map[string]string) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatHealth) WithOpaqueID(s string) func(*CatHealthRequest) { - return func(r *CatHealthRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.help.go b/opensearchapi/api.cat.help.go deleted file mode 100644 index 1489e23fa..000000000 --- a/opensearchapi/api.cat.help.go +++ /dev/null @@ -1,230 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newCatHelpFunc(t Transport) CatHelp { - return func(o ...func(*CatHelpRequest)) (*Response, error) { - var r = CatHelpRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatHelp returns help for the Cat APIs. -// -// -type CatHelp func(o ...func(*CatHelpRequest)) (*Response, error) - -// CatHelpRequest configures the Cat Help API request. -// -type CatHelpRequest struct { - Help *bool - S []string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatHelpRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cat")) - path.WriteString("/_cat") - - params = make(map[string]string) - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatHelp) WithContext(v context.Context) func(*CatHelpRequest) { - return func(r *CatHelpRequest) { - r.ctx = v - } -} - -// WithHelp - return help information. -// -func (f CatHelp) WithHelp(v bool) func(*CatHelpRequest) { - return func(r *CatHelpRequest) { - r.Help = &v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatHelp) WithS(v ...string) func(*CatHelpRequest) { - return func(r *CatHelpRequest) { - r.S = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatHelp) WithPretty() func(*CatHelpRequest) { - return func(r *CatHelpRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatHelp) WithHuman() func(*CatHelpRequest) { - return func(r *CatHelpRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatHelp) WithErrorTrace() func(*CatHelpRequest) { - return func(r *CatHelpRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatHelp) WithFilterPath(v ...string) func(*CatHelpRequest) { - return func(r *CatHelpRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatHelp) WithHeader(h map[string]string) func(*CatHelpRequest) { - return func(r *CatHelpRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatHelp) WithOpaqueID(s string) func(*CatHelpRequest) { - return func(r *CatHelpRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.indices.go b/opensearchapi/api.cat.indices.go deleted file mode 100644 index 71b2c330c..000000000 --- a/opensearchapi/api.cat.indices.go +++ /dev/null @@ -1,406 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatIndicesFunc(t Transport) CatIndices { - return func(o ...func(*CatIndicesRequest)) (*Response, error) { - var r = CatIndicesRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatIndices returns information about indices: number of primaries and replicas, document counts, disk size, ... -// -// -type CatIndices func(o ...func(*CatIndicesRequest)) (*Response, error) - -// CatIndicesRequest configures the Cat Indices API request. -// -type CatIndicesRequest struct { - Index []string - - Bytes string - ExpandWildcards string - Format string - H []string - Health string - Help *bool - IncludeUnloadedSegments *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Pri *bool - S []string - Time string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatIndicesRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("indices") + 1 + len(strings.Join(r.Index, ","))) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("indices") - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - - params = make(map[string]string) - - if r.Bytes != "" { - params["bytes"] = r.Bytes - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Health != "" { - params["health"] = r.Health - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.IncludeUnloadedSegments != nil { - params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pri != nil { - params["pri"] = strconv.FormatBool(*r.Pri) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.Time != "" { - params["time"] = r.Time - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatIndices) WithContext(v context.Context) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to limit the returned information. -// -func (f CatIndices) WithIndex(v ...string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.Index = v - } -} - -// WithBytes - the unit in which to display byte values. -// -func (f CatIndices) WithBytes(v string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.Bytes = v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f CatIndices) WithExpandWildcards(v string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.ExpandWildcards = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatIndices) WithFormat(v string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatIndices) WithH(v ...string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.H = v - } -} - -// WithHealth - a health status ("green", "yellow", or "red" to filter only indices matching the specified health status. -// -func (f CatIndices) WithHealth(v string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.Health = v - } -} - -// WithHelp - return help information. -// -func (f CatIndices) WithHelp(v bool) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.Help = &v - } -} - -// WithIncludeUnloadedSegments - if set to true segment stats will include stats for segments that are not currently loaded into memory. -// -func (f CatIndices) WithIncludeUnloadedSegments(v bool) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.IncludeUnloadedSegments = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f CatIndices) WithLocal(v bool) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatIndices) WithMasterTimeout(v time.Duration) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatIndices) WithClusterManagerTimeout(v time.Duration) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPri - set to true to return stats only for primary shards. -// -func (f CatIndices) WithPri(v bool) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.Pri = &v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatIndices) WithS(v ...string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.S = v - } -} - -// WithTime - the unit in which to display time values. -// -func (f CatIndices) WithTime(v string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.Time = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatIndices) WithV(v bool) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatIndices) WithPretty() func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatIndices) WithHuman() func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatIndices) WithErrorTrace() func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatIndices) WithFilterPath(v ...string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatIndices) WithHeader(h map[string]string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatIndices) WithOpaqueID(s string) func(*CatIndicesRequest) { - return func(r *CatIndicesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.master.go b/opensearchapi/api.cat.master.go deleted file mode 100644 index cea90dedf..000000000 --- a/opensearchapi/api.cat.master.go +++ /dev/null @@ -1,294 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatMasterFunc(t Transport) CatMaster { - return func(o ...func(*CatMasterRequest)) (*Response, error) { - var r = CatMasterRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatMaster returns information about the cluster-manager node. -// -// Deprecated: To promote inclusive language, please use CatClusterManager instead. -type CatMaster func(o ...func(*CatMasterRequest)) (*Response, error) - -// CatMasterRequest configures the Cat Master API request. -type CatMasterRequest struct { - Format string - H []string - Help *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -func (r CatMasterRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cat/master")) - path.WriteString("/_cat/master") - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -func (f CatMaster) WithContext(v context.Context) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.ctx = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -func (f CatMaster) WithFormat(v string) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -func (f CatMaster) WithH(v ...string) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.H = v - } -} - -// WithHelp - return help information. -func (f CatMaster) WithHelp(v bool) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.Help = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -func (f CatMaster) WithLocal(v bool) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -func (f CatMaster) WithMasterTimeout(v time.Duration) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -func (f CatMaster) WithClusterManagerTimeout(v time.Duration) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -func (f CatMaster) WithS(v ...string) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -func (f CatMaster) WithV(v bool) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -func (f CatMaster) WithPretty() func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -func (f CatMaster) WithHuman() func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -func (f CatMaster) WithErrorTrace() func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -func (f CatMaster) WithFilterPath(v ...string) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -func (f CatMaster) WithHeader(h map[string]string) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -func (f CatMaster) WithOpaqueID(s string) func(*CatMasterRequest) { - return func(r *CatMasterRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.nodeattrs.go b/opensearchapi/api.cat.nodeattrs.go deleted file mode 100644 index 7468b3542..000000000 --- a/opensearchapi/api.cat.nodeattrs.go +++ /dev/null @@ -1,311 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatNodeattrsFunc(t Transport) CatNodeattrs { - return func(o ...func(*CatNodeattrsRequest)) (*Response, error) { - var r = CatNodeattrsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatNodeattrs returns information about custom node attributes. -// -// -type CatNodeattrs func(o ...func(*CatNodeattrsRequest)) (*Response, error) - -// CatNodeattrsRequest configures the Cat Nodeattrs API request. -// -type CatNodeattrsRequest struct { - Format string - H []string - Help *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatNodeattrsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cat/nodeattrs")) - path.WriteString("/_cat/nodeattrs") - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatNodeattrs) WithContext(v context.Context) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.ctx = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatNodeattrs) WithFormat(v string) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatNodeattrs) WithH(v ...string) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatNodeattrs) WithHelp(v bool) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.Help = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f CatNodeattrs) WithLocal(v bool) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatNodeattrs) WithMasterTimeout(v time.Duration) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatNodeattrs) WithClusterManagerTimeout(v time.Duration) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatNodeattrs) WithS(v ...string) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatNodeattrs) WithV(v bool) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatNodeattrs) WithPretty() func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatNodeattrs) WithHuman() func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatNodeattrs) WithErrorTrace() func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatNodeattrs) WithFilterPath(v ...string) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatNodeattrs) WithHeader(h map[string]string) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatNodeattrs) WithOpaqueID(s string) func(*CatNodeattrsRequest) { - return func(r *CatNodeattrsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.nodes.go b/opensearchapi/api.cat.nodes.go deleted file mode 100644 index 90d770389..000000000 --- a/opensearchapi/api.cat.nodes.go +++ /dev/null @@ -1,363 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatNodesFunc(t Transport) CatNodes { - return func(o ...func(*CatNodesRequest)) (*Response, error) { - var r = CatNodesRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatNodes returns basic statistics about performance of cluster nodes. -// -// -type CatNodes func(o ...func(*CatNodesRequest)) (*Response, error) - -// CatNodesRequest configures the Cat Nodes API request. -// -type CatNodesRequest struct { - Bytes string - Format string - FullID *bool - H []string - Help *bool - IncludeUnloadedSegments *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - Time string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatNodesRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cat/nodes")) - path.WriteString("/_cat/nodes") - - params = make(map[string]string) - - if r.Bytes != "" { - params["bytes"] = r.Bytes - } - - if r.Format != "" { - params["format"] = r.Format - } - - if r.FullID != nil { - params["full_id"] = strconv.FormatBool(*r.FullID) - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.IncludeUnloadedSegments != nil { - params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.Time != "" { - params["time"] = r.Time - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatNodes) WithContext(v context.Context) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.ctx = v - } -} - -// WithBytes - the unit in which to display byte values. -// -func (f CatNodes) WithBytes(v string) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.Bytes = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatNodes) WithFormat(v string) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.Format = v - } -} - -// WithFullID - return the full node ID instead of the shortened version (default: false). -// -func (f CatNodes) WithFullID(v bool) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.FullID = &v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatNodes) WithH(v ...string) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatNodes) WithHelp(v bool) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.Help = &v - } -} - -// WithIncludeUnloadedSegments - if set to true segment stats will include stats for segments that are not currently loaded into memory. -// -func (f CatNodes) WithIncludeUnloadedSegments(v bool) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.IncludeUnloadedSegments = &v - } -} - -// WithLocal - calculate the selected nodes using the local cluster state rather than the state from cluster-manager node (default: false). -// -func (f CatNodes) WithLocal(v bool) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatNodes) WithMasterTimeout(v time.Duration) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatNodes) WithClusterManagerTimeout(v time.Duration) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatNodes) WithS(v ...string) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.S = v - } -} - -// WithTime - the unit in which to display time values. -// -func (f CatNodes) WithTime(v string) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.Time = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatNodes) WithV(v bool) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatNodes) WithPretty() func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatNodes) WithHuman() func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatNodes) WithErrorTrace() func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatNodes) WithFilterPath(v ...string) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatNodes) WithHeader(h map[string]string) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatNodes) WithOpaqueID(s string) func(*CatNodesRequest) { - return func(r *CatNodesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.pending_tasks.go b/opensearchapi/api.cat.pending_tasks.go deleted file mode 100644 index 992dae7f2..000000000 --- a/opensearchapi/api.cat.pending_tasks.go +++ /dev/null @@ -1,324 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatPendingTasksFunc(t Transport) CatPendingTasks { - return func(o ...func(*CatPendingTasksRequest)) (*Response, error) { - var r = CatPendingTasksRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatPendingTasks returns a concise representation of the cluster pending tasks. -// -// -type CatPendingTasks func(o ...func(*CatPendingTasksRequest)) (*Response, error) - -// CatPendingTasksRequest configures the Cat Pending Tasks API request. -// -type CatPendingTasksRequest struct { - Format string - H []string - Help *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - Time string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatPendingTasksRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cat/pending_tasks")) - path.WriteString("/_cat/pending_tasks") - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.Time != "" { - params["time"] = r.Time - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatPendingTasks) WithContext(v context.Context) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.ctx = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatPendingTasks) WithFormat(v string) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatPendingTasks) WithH(v ...string) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatPendingTasks) WithHelp(v bool) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.Help = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f CatPendingTasks) WithLocal(v bool) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatPendingTasks) WithMasterTimeout(v time.Duration) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatPendingTasks) WithClusterManagerTimeout(v time.Duration) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatPendingTasks) WithS(v ...string) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.S = v - } -} - -// WithTime - the unit in which to display time values. -// -func (f CatPendingTasks) WithTime(v string) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.Time = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatPendingTasks) WithV(v bool) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatPendingTasks) WithPretty() func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatPendingTasks) WithHuman() func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatPendingTasks) WithErrorTrace() func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatPendingTasks) WithFilterPath(v ...string) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatPendingTasks) WithHeader(h map[string]string) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatPendingTasks) WithOpaqueID(s string) func(*CatPendingTasksRequest) { - return func(r *CatPendingTasksRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.plugins.go b/opensearchapi/api.cat.plugins.go deleted file mode 100644 index bc8b1e6ab..000000000 --- a/opensearchapi/api.cat.plugins.go +++ /dev/null @@ -1,324 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatPluginsFunc(t Transport) CatPlugins { - return func(o ...func(*CatPluginsRequest)) (*Response, error) { - var r = CatPluginsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatPlugins returns information about installed plugins across nodes node. -// -// -type CatPlugins func(o ...func(*CatPluginsRequest)) (*Response, error) - -// CatPluginsRequest configures the Cat Plugins API request. -// -type CatPluginsRequest struct { - Format string - H []string - Help *bool - IncludeBootstrap *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatPluginsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cat/plugins")) - path.WriteString("/_cat/plugins") - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.IncludeBootstrap != nil { - params["include_bootstrap"] = strconv.FormatBool(*r.IncludeBootstrap) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatPlugins) WithContext(v context.Context) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.ctx = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatPlugins) WithFormat(v string) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatPlugins) WithH(v ...string) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatPlugins) WithHelp(v bool) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.Help = &v - } -} - -// WithIncludeBootstrap - include bootstrap plugins in the response. -// -func (f CatPlugins) WithIncludeBootstrap(v bool) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.IncludeBootstrap = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f CatPlugins) WithLocal(v bool) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatPlugins) WithMasterTimeout(v time.Duration) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatPlugins) WithClusterManagerTimeout(v time.Duration) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatPlugins) WithS(v ...string) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatPlugins) WithV(v bool) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatPlugins) WithPretty() func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatPlugins) WithHuman() func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatPlugins) WithErrorTrace() func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatPlugins) WithFilterPath(v ...string) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatPlugins) WithHeader(h map[string]string) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatPlugins) WithOpaqueID(s string) func(*CatPluginsRequest) { - return func(r *CatPluginsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.recovery.go b/opensearchapi/api.cat.recovery.go deleted file mode 100644 index 5db084137..000000000 --- a/opensearchapi/api.cat.recovery.go +++ /dev/null @@ -1,342 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newCatRecoveryFunc(t Transport) CatRecovery { - return func(o ...func(*CatRecoveryRequest)) (*Response, error) { - var r = CatRecoveryRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatRecovery returns information about index shard recoveries, both on-going completed. -// -// -type CatRecovery func(o ...func(*CatRecoveryRequest)) (*Response, error) - -// CatRecoveryRequest configures the Cat Recovery API request. -// -type CatRecoveryRequest struct { - Index []string - - ActiveOnly *bool - Bytes string - Detailed *bool - Format string - H []string - Help *bool - S []string - Time string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatRecoveryRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("recovery") + 1 + len(strings.Join(r.Index, ","))) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("recovery") - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - - params = make(map[string]string) - - if r.ActiveOnly != nil { - params["active_only"] = strconv.FormatBool(*r.ActiveOnly) - } - - if r.Bytes != "" { - params["bytes"] = r.Bytes - } - - if r.Detailed != nil { - params["detailed"] = strconv.FormatBool(*r.Detailed) - } - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if len(r.Index) > 0 { - params["index"] = strings.Join(r.Index, ",") - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.Time != "" { - params["time"] = r.Time - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatRecovery) WithContext(v context.Context) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.ctx = v - } -} - -// WithIndex - comma-separated list or wildcard expression of index names to limit the returned information. -// -func (f CatRecovery) WithIndex(v ...string) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.Index = v - } -} - -// WithActiveOnly - if `true`, the response only includes ongoing shard recoveries. -// -func (f CatRecovery) WithActiveOnly(v bool) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.ActiveOnly = &v - } -} - -// WithBytes - the unit in which to display byte values. -// -func (f CatRecovery) WithBytes(v string) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.Bytes = v - } -} - -// WithDetailed - if `true`, the response includes detailed information about shard recoveries. -// -func (f CatRecovery) WithDetailed(v bool) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.Detailed = &v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatRecovery) WithFormat(v string) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatRecovery) WithH(v ...string) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatRecovery) WithHelp(v bool) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.Help = &v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatRecovery) WithS(v ...string) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.S = v - } -} - -// WithTime - the unit in which to display time values. -// -func (f CatRecovery) WithTime(v string) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.Time = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatRecovery) WithV(v bool) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatRecovery) WithPretty() func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatRecovery) WithHuman() func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatRecovery) WithErrorTrace() func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatRecovery) WithFilterPath(v ...string) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatRecovery) WithHeader(h map[string]string) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatRecovery) WithOpaqueID(s string) func(*CatRecoveryRequest) { - return func(r *CatRecoveryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.repositories.go b/opensearchapi/api.cat.repositories.go deleted file mode 100644 index c7057a981..000000000 --- a/opensearchapi/api.cat.repositories.go +++ /dev/null @@ -1,311 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatRepositoriesFunc(t Transport) CatRepositories { - return func(o ...func(*CatRepositoriesRequest)) (*Response, error) { - var r = CatRepositoriesRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatRepositories returns information about snapshot repositories registered in the cluster. -// -// -type CatRepositories func(o ...func(*CatRepositoriesRequest)) (*Response, error) - -// CatRepositoriesRequest configures the Cat Repositories API request. -// -type CatRepositoriesRequest struct { - Format string - H []string - Help *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatRepositoriesRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cat/repositories")) - path.WriteString("/_cat/repositories") - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatRepositories) WithContext(v context.Context) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.ctx = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatRepositories) WithFormat(v string) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatRepositories) WithH(v ...string) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatRepositories) WithHelp(v bool) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.Help = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f CatRepositories) WithLocal(v bool) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatRepositories) WithMasterTimeout(v time.Duration) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatRepositories) WithClusterManagerTimeout(v time.Duration) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatRepositories) WithS(v ...string) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatRepositories) WithV(v bool) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatRepositories) WithPretty() func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatRepositories) WithHuman() func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatRepositories) WithErrorTrace() func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatRepositories) WithFilterPath(v ...string) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatRepositories) WithHeader(h map[string]string) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatRepositories) WithOpaqueID(s string) func(*CatRepositoriesRequest) { - return func(r *CatRepositoriesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.segments.go b/opensearchapi/api.cat.segments.go deleted file mode 100644 index aed566ee1..000000000 --- a/opensearchapi/api.cat.segments.go +++ /dev/null @@ -1,299 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newCatSegmentsFunc(t Transport) CatSegments { - return func(o ...func(*CatSegmentsRequest)) (*Response, error) { - var r = CatSegmentsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatSegments provides low-level information about the segments in the shards of an index. -// -// -type CatSegments func(o ...func(*CatSegmentsRequest)) (*Response, error) - -// CatSegmentsRequest configures the Cat Segments API request. -// -type CatSegmentsRequest struct { - Index []string - - Bytes string - Format string - H []string - Help *bool - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatSegmentsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("segments") + 1 + len(strings.Join(r.Index, ","))) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("segments") - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - - params = make(map[string]string) - - if r.Bytes != "" { - params["bytes"] = r.Bytes - } - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatSegments) WithContext(v context.Context) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to limit the returned information. -// -func (f CatSegments) WithIndex(v ...string) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.Index = v - } -} - -// WithBytes - the unit in which to display byte values. -// -func (f CatSegments) WithBytes(v string) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.Bytes = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatSegments) WithFormat(v string) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatSegments) WithH(v ...string) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatSegments) WithHelp(v bool) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.Help = &v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatSegments) WithS(v ...string) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatSegments) WithV(v bool) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatSegments) WithPretty() func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatSegments) WithHuman() func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatSegments) WithErrorTrace() func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatSegments) WithFilterPath(v ...string) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatSegments) WithHeader(h map[string]string) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatSegments) WithOpaqueID(s string) func(*CatSegmentsRequest) { - return func(r *CatSegmentsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.shards.go b/opensearchapi/api.cat.shards.go deleted file mode 100644 index 9d6549355..000000000 --- a/opensearchapi/api.cat.shards.go +++ /dev/null @@ -1,354 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatShardsFunc(t Transport) CatShards { - return func(o ...func(*CatShardsRequest)) (*Response, error) { - var r = CatShardsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatShards provides a detailed view of shard allocation on nodes. -// -// -type CatShards func(o ...func(*CatShardsRequest)) (*Response, error) - -// CatShardsRequest configures the Cat Shards API request. -// -type CatShardsRequest struct { - Index []string - - Bytes string - Format string - H []string - Help *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - Time string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatShardsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("shards") + 1 + len(strings.Join(r.Index, ","))) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("shards") - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - - params = make(map[string]string) - - if r.Bytes != "" { - params["bytes"] = r.Bytes - } - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.Time != "" { - params["time"] = r.Time - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatShards) WithContext(v context.Context) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to limit the returned information. -// -func (f CatShards) WithIndex(v ...string) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.Index = v - } -} - -// WithBytes - the unit in which to display byte values. -// -func (f CatShards) WithBytes(v string) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.Bytes = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatShards) WithFormat(v string) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatShards) WithH(v ...string) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatShards) WithHelp(v bool) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.Help = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f CatShards) WithLocal(v bool) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatShards) WithMasterTimeout(v time.Duration) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatShards) WithClusterManagerTimeout(v time.Duration) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatShards) WithS(v ...string) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.S = v - } -} - -// WithTime - the unit in which to display time values. -// -func (f CatShards) WithTime(v string) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.Time = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatShards) WithV(v bool) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatShards) WithPretty() func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatShards) WithHuman() func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatShards) WithErrorTrace() func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatShards) WithFilterPath(v ...string) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatShards) WithHeader(h map[string]string) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatShards) WithOpaqueID(s string) func(*CatShardsRequest) { - return func(r *CatShardsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.snapshots.go b/opensearchapi/api.cat.snapshots.go deleted file mode 100644 index 1c8e4021b..000000000 --- a/opensearchapi/api.cat.snapshots.go +++ /dev/null @@ -1,341 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatSnapshotsFunc(t Transport) CatSnapshots { - return func(o ...func(*CatSnapshotsRequest)) (*Response, error) { - var r = CatSnapshotsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatSnapshots returns all snapshots in a specific repository. -// -// -type CatSnapshots func(o ...func(*CatSnapshotsRequest)) (*Response, error) - -// CatSnapshotsRequest configures the Cat Snapshots API request. -// -type CatSnapshotsRequest struct { - Repository []string - - Format string - H []string - Help *bool - IgnoreUnavailable *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - Time string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatSnapshotsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("snapshots") + 1 + len(strings.Join(r.Repository, ","))) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("snapshots") - if len(r.Repository) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Repository, ",")) - } - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.Time != "" { - params["time"] = r.Time - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatSnapshots) WithContext(v context.Context) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.ctx = v - } -} - -// WithRepository - name of repository from which to fetch the snapshot information. -// -func (f CatSnapshots) WithRepository(v ...string) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.Repository = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatSnapshots) WithFormat(v string) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatSnapshots) WithH(v ...string) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatSnapshots) WithHelp(v bool) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.Help = &v - } -} - -// WithIgnoreUnavailable - set to true to ignore unavailable snapshots. -// -func (f CatSnapshots) WithIgnoreUnavailable(v bool) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatSnapshots) WithMasterTimeout(v time.Duration) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatSnapshots) WithClusterManagerTimeout(v time.Duration) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatSnapshots) WithS(v ...string) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.S = v - } -} - -// WithTime - the unit in which to display time values. -// -func (f CatSnapshots) WithTime(v string) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.Time = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatSnapshots) WithV(v bool) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatSnapshots) WithPretty() func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatSnapshots) WithHuman() func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatSnapshots) WithErrorTrace() func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatSnapshots) WithFilterPath(v ...string) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatSnapshots) WithHeader(h map[string]string) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatSnapshots) WithOpaqueID(s string) func(*CatSnapshotsRequest) { - return func(r *CatSnapshotsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.tasks.go b/opensearchapi/api.cat.tasks.go deleted file mode 100644 index 3592808f7..000000000 --- a/opensearchapi/api.cat.tasks.go +++ /dev/null @@ -1,334 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newCatTasksFunc(t Transport) CatTasks { - return func(o ...func(*CatTasksRequest)) (*Response, error) { - var r = CatTasksRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatTasks returns information about the tasks currently executing on one or more nodes in the cluster. -// -// -type CatTasks func(o ...func(*CatTasksRequest)) (*Response, error) - -// CatTasksRequest configures the Cat Tasks API request. -// -type CatTasksRequest struct { - Actions []string - Detailed *bool - Format string - H []string - Help *bool - Nodes []string - ParentTaskID string - S []string - Time string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatTasksRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cat/tasks")) - path.WriteString("/_cat/tasks") - - params = make(map[string]string) - - if len(r.Actions) > 0 { - params["actions"] = strings.Join(r.Actions, ",") - } - - if r.Detailed != nil { - params["detailed"] = strconv.FormatBool(*r.Detailed) - } - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if len(r.Nodes) > 0 { - params["nodes"] = strings.Join(r.Nodes, ",") - } - - if r.ParentTaskID != "" { - params["parent_task_id"] = r.ParentTaskID - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.Time != "" { - params["time"] = r.Time - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatTasks) WithContext(v context.Context) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.ctx = v - } -} - -// WithActions - a list of actions that should be returned. leave empty to return all.. -// -func (f CatTasks) WithActions(v ...string) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.Actions = v - } -} - -// WithDetailed - return detailed task information (default: false). -// -func (f CatTasks) WithDetailed(v bool) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.Detailed = &v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatTasks) WithFormat(v string) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatTasks) WithH(v ...string) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatTasks) WithHelp(v bool) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.Help = &v - } -} - -// WithNodes - a list of node ids or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes. -// -func (f CatTasks) WithNodes(v ...string) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.Nodes = v - } -} - -// WithParentTaskID - return tasks with specified parent task ID (node_id:task_number). set to -1 to return all.. -// -func (f CatTasks) WithParentTaskID(v string) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.ParentTaskID = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatTasks) WithS(v ...string) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.S = v - } -} - -// WithTime - the unit in which to display time values. -// -func (f CatTasks) WithTime(v string) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.Time = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatTasks) WithV(v bool) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatTasks) WithPretty() func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatTasks) WithHuman() func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatTasks) WithErrorTrace() func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatTasks) WithFilterPath(v ...string) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatTasks) WithHeader(h map[string]string) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatTasks) WithOpaqueID(s string) func(*CatTasksRequest) { - return func(r *CatTasksRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.templates.go b/opensearchapi/api.cat.templates.go deleted file mode 100644 index c4d343eed..000000000 --- a/opensearchapi/api.cat.templates.go +++ /dev/null @@ -1,328 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatTemplatesFunc(t Transport) CatTemplates { - return func(o ...func(*CatTemplatesRequest)) (*Response, error) { - var r = CatTemplatesRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatTemplates returns information about existing templates. -// -// -type CatTemplates func(o ...func(*CatTemplatesRequest)) (*Response, error) - -// CatTemplatesRequest configures the Cat Templates API request. -// -type CatTemplatesRequest struct { - Name string - - Format string - H []string - Help *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatTemplatesRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("templates") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("templates") - if r.Name != "" { - path.WriteString("/") - path.WriteString(r.Name) - } - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatTemplates) WithContext(v context.Context) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.ctx = v - } -} - -// WithName - a pattern that returned template names must match. -// -func (f CatTemplates) WithName(v string) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.Name = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatTemplates) WithFormat(v string) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatTemplates) WithH(v ...string) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatTemplates) WithHelp(v bool) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.Help = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f CatTemplates) WithLocal(v bool) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatTemplates) WithMasterTimeout(v time.Duration) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatTemplates) WithClusterManagerTimeout(v time.Duration) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatTemplates) WithS(v ...string) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.S = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatTemplates) WithV(v bool) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatTemplates) WithPretty() func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatTemplates) WithHuman() func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatTemplates) WithErrorTrace() func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatTemplates) WithFilterPath(v ...string) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatTemplates) WithHeader(h map[string]string) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatTemplates) WithOpaqueID(s string) func(*CatTemplatesRequest) { - return func(r *CatTemplatesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cat.thread_pool.go b/opensearchapi/api.cat.thread_pool.go deleted file mode 100644 index fb1ea0d71..000000000 --- a/opensearchapi/api.cat.thread_pool.go +++ /dev/null @@ -1,342 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newCatThreadPoolFunc(t Transport) CatThreadPool { - return func(o ...func(*CatThreadPoolRequest)) (*Response, error) { - var r = CatThreadPoolRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// CatThreadPool returns cluster-wide thread pool statistics per node. -// By default the active, queue and rejected statistics are returned for all thread pools. -// -// -type CatThreadPool func(o ...func(*CatThreadPoolRequest)) (*Response, error) - -// CatThreadPoolRequest configures the Cat Thread Pool API request. -// -type CatThreadPoolRequest struct { - ThreadPoolPatterns []string - - Format string - H []string - Help *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - S []string - Size string - V *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CatThreadPoolRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cat") + 1 + len("thread_pool") + 1 + len(strings.Join(r.ThreadPoolPatterns, ","))) - path.WriteString("/") - path.WriteString("_cat") - path.WriteString("/") - path.WriteString("thread_pool") - if len(r.ThreadPoolPatterns) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.ThreadPoolPatterns, ",")) - } - - params = make(map[string]string) - - if r.Format != "" { - params["format"] = r.Format - } - - if len(r.H) > 0 { - params["h"] = strings.Join(r.H, ",") - } - - if r.Help != nil { - params["help"] = strconv.FormatBool(*r.Help) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.S) > 0 { - params["s"] = strings.Join(r.S, ",") - } - - if r.Size != "" { - params["size"] = r.Size - } - - if r.V != nil { - params["v"] = strconv.FormatBool(*r.V) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f CatThreadPool) WithContext(v context.Context) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.ctx = v - } -} - -// WithThreadPoolPatterns - a list of regular-expressions to filter the thread pools in the output. -// -func (f CatThreadPool) WithThreadPoolPatterns(v ...string) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.ThreadPoolPatterns = v - } -} - -// WithFormat - a short version of the accept header, e.g. json, yaml. -// -func (f CatThreadPool) WithFormat(v string) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.Format = v - } -} - -// WithH - comma-separated list of column names to display. -// -func (f CatThreadPool) WithH(v ...string) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.H = v - } -} - -// WithHelp - return help information. -// -func (f CatThreadPool) WithHelp(v bool) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.Help = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f CatThreadPool) WithLocal(v bool) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f CatThreadPool) WithMasterTimeout(v time.Duration) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f CatThreadPool) WithClusterManagerTimeout(v time.Duration) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithS - comma-separated list of column names or column aliases to sort by. -// -func (f CatThreadPool) WithS(v ...string) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.S = v - } -} - -// WithSize - the multiplier in which to display values. -// -func (f CatThreadPool) WithSize(v string) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.Size = v - } -} - -// WithV - verbose mode. display column headers. -// -func (f CatThreadPool) WithV(v bool) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.V = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f CatThreadPool) WithPretty() func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f CatThreadPool) WithHuman() func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f CatThreadPool) WithErrorTrace() func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f CatThreadPool) WithFilterPath(v ...string) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f CatThreadPool) WithHeader(h map[string]string) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f CatThreadPool) WithOpaqueID(s string) func(*CatThreadPoolRequest) { - return func(r *CatThreadPoolRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.clear_scroll.go b/opensearchapi/api.clear_scroll.go deleted file mode 100644 index 4fe1660a3..000000000 --- a/opensearchapi/api.clear_scroll.go +++ /dev/null @@ -1,234 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" -) - -func newClearScrollFunc(t Transport) ClearScroll { - return func(o ...func(*ClearScrollRequest)) (*Response, error) { - var r = ClearScrollRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClearScroll explicitly clears the search context for a scroll. -// -// -type ClearScroll func(o ...func(*ClearScrollRequest)) (*Response, error) - -// ClearScrollRequest configures the Clear Scroll API request. -// -type ClearScrollRequest struct { - Body io.Reader - - ScrollID []string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClearScrollRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len("_search") + 1 + len("scroll") + 1 + len(strings.Join(r.ScrollID, ","))) - path.WriteString("/") - path.WriteString("_search") - path.WriteString("/") - path.WriteString("scroll") - if len(r.ScrollID) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.ScrollID, ",")) - } - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClearScroll) WithContext(v context.Context) func(*ClearScrollRequest) { - return func(r *ClearScrollRequest) { - r.ctx = v - } -} - -// WithBody - A comma-separated list of scroll IDs to clear if none was specified via the scroll_id parameter. -// -func (f ClearScroll) WithBody(v io.Reader) func(*ClearScrollRequest) { - return func(r *ClearScrollRequest) { - r.Body = v - } -} - -// WithScrollID - a list of scroll ids to clear. -// -func (f ClearScroll) WithScrollID(v ...string) func(*ClearScrollRequest) { - return func(r *ClearScrollRequest) { - r.ScrollID = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClearScroll) WithPretty() func(*ClearScrollRequest) { - return func(r *ClearScrollRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClearScroll) WithHuman() func(*ClearScrollRequest) { - return func(r *ClearScrollRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClearScroll) WithErrorTrace() func(*ClearScrollRequest) { - return func(r *ClearScrollRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClearScroll) WithFilterPath(v ...string) func(*ClearScrollRequest) { - return func(r *ClearScrollRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClearScroll) WithHeader(h map[string]string) func(*ClearScrollRequest) { - return func(r *ClearScrollRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClearScroll) WithOpaqueID(s string) func(*ClearScrollRequest) { - return func(r *ClearScrollRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.allocation_explain.go b/opensearchapi/api.cluster.allocation_explain.go deleted file mode 100644 index 089f13ba8..000000000 --- a/opensearchapi/api.cluster.allocation_explain.go +++ /dev/null @@ -1,245 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newClusterAllocationExplainFunc(t Transport) ClusterAllocationExplain { - return func(o ...func(*ClusterAllocationExplainRequest)) (*Response, error) { - var r = ClusterAllocationExplainRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterAllocationExplain provides explanations for shard allocations in the cluster. -// -// -type ClusterAllocationExplain func(o ...func(*ClusterAllocationExplainRequest)) (*Response, error) - -// ClusterAllocationExplainRequest configures the Cluster Allocation Explain API request. -// -type ClusterAllocationExplainRequest struct { - Body io.Reader - - IncludeDiskInfo *bool - IncludeYesDecisions *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterAllocationExplainRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(len("/_cluster/allocation/explain")) - path.WriteString("/_cluster/allocation/explain") - - params = make(map[string]string) - - if r.IncludeDiskInfo != nil { - params["include_disk_info"] = strconv.FormatBool(*r.IncludeDiskInfo) - } - - if r.IncludeYesDecisions != nil { - params["include_yes_decisions"] = strconv.FormatBool(*r.IncludeYesDecisions) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterAllocationExplain) WithContext(v context.Context) func(*ClusterAllocationExplainRequest) { - return func(r *ClusterAllocationExplainRequest) { - r.ctx = v - } -} - -// WithBody - The index, shard, and primary flag to explain. Empty means 'explain the first unassigned shard'. -// -func (f ClusterAllocationExplain) WithBody(v io.Reader) func(*ClusterAllocationExplainRequest) { - return func(r *ClusterAllocationExplainRequest) { - r.Body = v - } -} - -// WithIncludeDiskInfo - return information about disk usage and shard sizes (default: false). -// -func (f ClusterAllocationExplain) WithIncludeDiskInfo(v bool) func(*ClusterAllocationExplainRequest) { - return func(r *ClusterAllocationExplainRequest) { - r.IncludeDiskInfo = &v - } -} - -// WithIncludeYesDecisions - return 'yes' decisions in explanation (default: false). -// -func (f ClusterAllocationExplain) WithIncludeYesDecisions(v bool) func(*ClusterAllocationExplainRequest) { - return func(r *ClusterAllocationExplainRequest) { - r.IncludeYesDecisions = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterAllocationExplain) WithPretty() func(*ClusterAllocationExplainRequest) { - return func(r *ClusterAllocationExplainRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterAllocationExplain) WithHuman() func(*ClusterAllocationExplainRequest) { - return func(r *ClusterAllocationExplainRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterAllocationExplain) WithErrorTrace() func(*ClusterAllocationExplainRequest) { - return func(r *ClusterAllocationExplainRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterAllocationExplain) WithFilterPath(v ...string) func(*ClusterAllocationExplainRequest) { - return func(r *ClusterAllocationExplainRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterAllocationExplain) WithHeader(h map[string]string) func(*ClusterAllocationExplainRequest) { - return func(r *ClusterAllocationExplainRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterAllocationExplain) WithOpaqueID(s string) func(*ClusterAllocationExplainRequest) { - return func(r *ClusterAllocationExplainRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.delete_component_template.go b/opensearchapi/api.cluster.delete_component_template.go deleted file mode 100644 index 407848617..000000000 --- a/opensearchapi/api.cluster.delete_component_template.go +++ /dev/null @@ -1,250 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newClusterDeleteComponentTemplateFunc(t Transport) ClusterDeleteComponentTemplate { - return func(name string, o ...func(*ClusterDeleteComponentTemplateRequest)) (*Response, error) { - var r = ClusterDeleteComponentTemplateRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterDeleteComponentTemplate deletes a component template -// -// -type ClusterDeleteComponentTemplate func(name string, o ...func(*ClusterDeleteComponentTemplateRequest)) (*Response, error) - -// ClusterDeleteComponentTemplateRequest configures the Cluster Delete Component Template API request. -// -type ClusterDeleteComponentTemplateRequest struct { - Name string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterDeleteComponentTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len("_component_template") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_component_template") - path.WriteString("/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterDeleteComponentTemplate) WithContext(v context.Context) func(*ClusterDeleteComponentTemplateRequest) { - return func(r *ClusterDeleteComponentTemplateRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f ClusterDeleteComponentTemplate) WithMasterTimeout(v time.Duration) func(*ClusterDeleteComponentTemplateRequest) { - return func(r *ClusterDeleteComponentTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f ClusterDeleteComponentTemplate) WithClusterManagerTimeout(v time.Duration) func(*ClusterDeleteComponentTemplateRequest) { - return func(r *ClusterDeleteComponentTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f ClusterDeleteComponentTemplate) WithTimeout(v time.Duration) func(*ClusterDeleteComponentTemplateRequest) { - return func(r *ClusterDeleteComponentTemplateRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterDeleteComponentTemplate) WithPretty() func(*ClusterDeleteComponentTemplateRequest) { - return func(r *ClusterDeleteComponentTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterDeleteComponentTemplate) WithHuman() func(*ClusterDeleteComponentTemplateRequest) { - return func(r *ClusterDeleteComponentTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterDeleteComponentTemplate) WithErrorTrace() func(*ClusterDeleteComponentTemplateRequest) { - return func(r *ClusterDeleteComponentTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterDeleteComponentTemplate) WithFilterPath(v ...string) func(*ClusterDeleteComponentTemplateRequest) { - return func(r *ClusterDeleteComponentTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterDeleteComponentTemplate) WithHeader(h map[string]string) func(*ClusterDeleteComponentTemplateRequest) { - return func(r *ClusterDeleteComponentTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterDeleteComponentTemplate) WithOpaqueID(s string) func(*ClusterDeleteComponentTemplateRequest) { - return func(r *ClusterDeleteComponentTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.delete_voting_config_exclusions.go b/opensearchapi/api.cluster.delete_voting_config_exclusions.go deleted file mode 100644 index dcc7d8811..000000000 --- a/opensearchapi/api.cluster.delete_voting_config_exclusions.go +++ /dev/null @@ -1,217 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newClusterDeleteVotingConfigExclusionsFunc(t Transport) ClusterDeleteVotingConfigExclusions { - return func(o ...func(*ClusterDeleteVotingConfigExclusionsRequest)) (*Response, error) { - var r = ClusterDeleteVotingConfigExclusionsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterDeleteVotingConfigExclusions clears cluster voting config exclusions. -// -// -type ClusterDeleteVotingConfigExclusions func(o ...func(*ClusterDeleteVotingConfigExclusionsRequest)) (*Response, error) - -// ClusterDeleteVotingConfigExclusionsRequest configures the Cluster Delete Voting Config Exclusions API request. -// -type ClusterDeleteVotingConfigExclusionsRequest struct { - WaitForRemoval *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterDeleteVotingConfigExclusionsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(len("/_cluster/voting_config_exclusions")) - path.WriteString("/_cluster/voting_config_exclusions") - - params = make(map[string]string) - - if r.WaitForRemoval != nil { - params["wait_for_removal"] = strconv.FormatBool(*r.WaitForRemoval) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterDeleteVotingConfigExclusions) WithContext(v context.Context) func(*ClusterDeleteVotingConfigExclusionsRequest) { - return func(r *ClusterDeleteVotingConfigExclusionsRequest) { - r.ctx = v - } -} - -// WithWaitForRemoval - specifies whether to wait for all excluded nodes to be removed from the cluster before clearing the voting configuration exclusions list.. -// -func (f ClusterDeleteVotingConfigExclusions) WithWaitForRemoval(v bool) func(*ClusterDeleteVotingConfigExclusionsRequest) { - return func(r *ClusterDeleteVotingConfigExclusionsRequest) { - r.WaitForRemoval = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterDeleteVotingConfigExclusions) WithPretty() func(*ClusterDeleteVotingConfigExclusionsRequest) { - return func(r *ClusterDeleteVotingConfigExclusionsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterDeleteVotingConfigExclusions) WithHuman() func(*ClusterDeleteVotingConfigExclusionsRequest) { - return func(r *ClusterDeleteVotingConfigExclusionsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterDeleteVotingConfigExclusions) WithErrorTrace() func(*ClusterDeleteVotingConfigExclusionsRequest) { - return func(r *ClusterDeleteVotingConfigExclusionsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterDeleteVotingConfigExclusions) WithFilterPath(v ...string) func(*ClusterDeleteVotingConfigExclusionsRequest) { - return func(r *ClusterDeleteVotingConfigExclusionsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterDeleteVotingConfigExclusions) WithHeader(h map[string]string) func(*ClusterDeleteVotingConfigExclusionsRequest) { - return func(r *ClusterDeleteVotingConfigExclusionsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterDeleteVotingConfigExclusions) WithOpaqueID(s string) func(*ClusterDeleteVotingConfigExclusionsRequest) { - return func(r *ClusterDeleteVotingConfigExclusionsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.exists_component_template.go b/opensearchapi/api.cluster.exists_component_template.go deleted file mode 100644 index d1fb93b84..000000000 --- a/opensearchapi/api.cluster.exists_component_template.go +++ /dev/null @@ -1,251 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newClusterExistsComponentTemplateFunc(t Transport) ClusterExistsComponentTemplate { - return func(name string, o ...func(*ClusterExistsComponentTemplateRequest)) (*Response, error) { - var r = ClusterExistsComponentTemplateRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterExistsComponentTemplate returns information about whether a particular component template exist -// -// -type ClusterExistsComponentTemplate func(name string, o ...func(*ClusterExistsComponentTemplateRequest)) (*Response, error) - -// ClusterExistsComponentTemplateRequest configures the Cluster Exists Component Template API request. -// -type ClusterExistsComponentTemplateRequest struct { - Name string - - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterExistsComponentTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "HEAD" - - path.Grow(1 + len("_component_template") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_component_template") - path.WriteString("/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterExistsComponentTemplate) WithContext(v context.Context) func(*ClusterExistsComponentTemplateRequest) { - return func(r *ClusterExistsComponentTemplateRequest) { - r.ctx = v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f ClusterExistsComponentTemplate) WithLocal(v bool) func(*ClusterExistsComponentTemplateRequest) { - return func(r *ClusterExistsComponentTemplateRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f ClusterExistsComponentTemplate) WithMasterTimeout(v time.Duration) func(*ClusterExistsComponentTemplateRequest) { - return func(r *ClusterExistsComponentTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f ClusterExistsComponentTemplate) WithClusterManagerTimeout(v time.Duration) func(*ClusterExistsComponentTemplateRequest) { - return func(r *ClusterExistsComponentTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterExistsComponentTemplate) WithPretty() func(*ClusterExistsComponentTemplateRequest) { - return func(r *ClusterExistsComponentTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterExistsComponentTemplate) WithHuman() func(*ClusterExistsComponentTemplateRequest) { - return func(r *ClusterExistsComponentTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterExistsComponentTemplate) WithErrorTrace() func(*ClusterExistsComponentTemplateRequest) { - return func(r *ClusterExistsComponentTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterExistsComponentTemplate) WithFilterPath(v ...string) func(*ClusterExistsComponentTemplateRequest) { - return func(r *ClusterExistsComponentTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterExistsComponentTemplate) WithHeader(h map[string]string) func(*ClusterExistsComponentTemplateRequest) { - return func(r *ClusterExistsComponentTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterExistsComponentTemplate) WithOpaqueID(s string) func(*ClusterExistsComponentTemplateRequest) { - return func(r *ClusterExistsComponentTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.get_component_template.go b/opensearchapi/api.cluster.get_component_template.go deleted file mode 100644 index b883b8f67..000000000 --- a/opensearchapi/api.cluster.get_component_template.go +++ /dev/null @@ -1,261 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newClusterGetComponentTemplateFunc(t Transport) ClusterGetComponentTemplate { - return func(o ...func(*ClusterGetComponentTemplateRequest)) (*Response, error) { - var r = ClusterGetComponentTemplateRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterGetComponentTemplate returns one or more component templates -// -// -type ClusterGetComponentTemplate func(o ...func(*ClusterGetComponentTemplateRequest)) (*Response, error) - -// ClusterGetComponentTemplateRequest configures the Cluster Get Component Template API request. -// -type ClusterGetComponentTemplateRequest struct { - Name []string - - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterGetComponentTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_component_template") + 1 + len(strings.Join(r.Name, ","))) - path.WriteString("/") - path.WriteString("_component_template") - if len(r.Name) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Name, ",")) - } - - params = make(map[string]string) - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterGetComponentTemplate) WithContext(v context.Context) func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - r.ctx = v - } -} - -// WithName - the comma separated names of the component templates. -// -func (f ClusterGetComponentTemplate) WithName(v ...string) func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - r.Name = v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f ClusterGetComponentTemplate) WithLocal(v bool) func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f ClusterGetComponentTemplate) WithMasterTimeout(v time.Duration) func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f ClusterGetComponentTemplate) WithClusterManagerTimeout(v time.Duration) func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterGetComponentTemplate) WithPretty() func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterGetComponentTemplate) WithHuman() func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterGetComponentTemplate) WithErrorTrace() func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterGetComponentTemplate) WithFilterPath(v ...string) func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterGetComponentTemplate) WithHeader(h map[string]string) func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterGetComponentTemplate) WithOpaqueID(s string) func(*ClusterGetComponentTemplateRequest) { - return func(r *ClusterGetComponentTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.get_settings.go b/opensearchapi/api.cluster.get_settings.go deleted file mode 100644 index fd0608f77..000000000 --- a/opensearchapi/api.cluster.get_settings.go +++ /dev/null @@ -1,272 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newClusterGetSettingsFunc(t Transport) ClusterGetSettings { - return func(o ...func(*ClusterGetSettingsRequest)) (*Response, error) { - var r = ClusterGetSettingsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterGetSettings returns cluster settings. -// -// -type ClusterGetSettings func(o ...func(*ClusterGetSettingsRequest)) (*Response, error) - -// ClusterGetSettingsRequest configures the Cluster Get Settings API request. -// -type ClusterGetSettingsRequest struct { - FlatSettings *bool - IncludeDefaults *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterGetSettingsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cluster/settings")) - path.WriteString("/_cluster/settings") - - params = make(map[string]string) - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.IncludeDefaults != nil { - params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterGetSettings) WithContext(v context.Context) func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - r.ctx = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f ClusterGetSettings) WithFlatSettings(v bool) func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - r.FlatSettings = &v - } -} - -// WithIncludeDefaults - whether to return all default clusters setting.. -// -func (f ClusterGetSettings) WithIncludeDefaults(v bool) func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - r.IncludeDefaults = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f ClusterGetSettings) WithMasterTimeout(v time.Duration) func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f ClusterGetSettings) WithClusterManagerTimeout(v time.Duration) func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f ClusterGetSettings) WithTimeout(v time.Duration) func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterGetSettings) WithPretty() func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterGetSettings) WithHuman() func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterGetSettings) WithErrorTrace() func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterGetSettings) WithFilterPath(v ...string) func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterGetSettings) WithHeader(h map[string]string) func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterGetSettings) WithOpaqueID(s string) func(*ClusterGetSettingsRequest) { - return func(r *ClusterGetSettingsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.health.go b/opensearchapi/api.cluster.health.go deleted file mode 100644 index 05869c546..000000000 --- a/opensearchapi/api.cluster.health.go +++ /dev/null @@ -1,380 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newClusterHealthFunc(t Transport) ClusterHealth { - return func(o ...func(*ClusterHealthRequest)) (*Response, error) { - var r = ClusterHealthRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterHealth returns basic information about the health of the cluster. -// -// -type ClusterHealth func(o ...func(*ClusterHealthRequest)) (*Response, error) - -// ClusterHealthRequest configures the Cluster Health API request. -// -type ClusterHealthRequest struct { - Index []string - - ExpandWildcards string - Level string - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - WaitForActiveShards string - WaitForEvents string - WaitForNoInitializingShards *bool - WaitForNoRelocatingShards *bool - WaitForNodes string - WaitForStatus string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterHealthRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cluster") + 1 + len("health") + 1 + len(strings.Join(r.Index, ","))) - path.WriteString("/") - path.WriteString("_cluster") - path.WriteString("/") - path.WriteString("health") - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - - params = make(map[string]string) - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Level != "" { - params["level"] = r.Level - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.WaitForEvents != "" { - params["wait_for_events"] = r.WaitForEvents - } - - if r.WaitForNoInitializingShards != nil { - params["wait_for_no_initializing_shards"] = strconv.FormatBool(*r.WaitForNoInitializingShards) - } - - if r.WaitForNoRelocatingShards != nil { - params["wait_for_no_relocating_shards"] = strconv.FormatBool(*r.WaitForNoRelocatingShards) - } - - if r.WaitForNodes != "" { - params["wait_for_nodes"] = r.WaitForNodes - } - - if r.WaitForStatus != "" { - params["wait_for_status"] = r.WaitForStatus - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterHealth) WithContext(v context.Context) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.ctx = v - } -} - -// WithIndex - limit the information returned to a specific index. -// -func (f ClusterHealth) WithIndex(v ...string) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.Index = v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f ClusterHealth) WithExpandWildcards(v string) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.ExpandWildcards = v - } -} - -// WithLevel - specify the level of detail for returned information. -// -func (f ClusterHealth) WithLevel(v string) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.Level = v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f ClusterHealth) WithLocal(v bool) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f ClusterHealth) WithMasterTimeout(v time.Duration) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f ClusterHealth) WithClusterManagerTimeout(v time.Duration) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f ClusterHealth) WithTimeout(v time.Duration) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - wait until the specified number of shards is active. -// -func (f ClusterHealth) WithWaitForActiveShards(v string) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.WaitForActiveShards = v - } -} - -// WithWaitForEvents - wait until all currently queued events with the given priority are processed. -// -func (f ClusterHealth) WithWaitForEvents(v string) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.WaitForEvents = v - } -} - -// WithWaitForNoInitializingShards - whether to wait until there are no initializing shards in the cluster. -// -func (f ClusterHealth) WithWaitForNoInitializingShards(v bool) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.WaitForNoInitializingShards = &v - } -} - -// WithWaitForNoRelocatingShards - whether to wait until there are no relocating shards in the cluster. -// -func (f ClusterHealth) WithWaitForNoRelocatingShards(v bool) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.WaitForNoRelocatingShards = &v - } -} - -// WithWaitForNodes - wait until the specified number of nodes is available. -// -func (f ClusterHealth) WithWaitForNodes(v string) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.WaitForNodes = v - } -} - -// WithWaitForStatus - wait until cluster is in a specific state. -// -func (f ClusterHealth) WithWaitForStatus(v string) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.WaitForStatus = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterHealth) WithPretty() func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterHealth) WithHuman() func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterHealth) WithErrorTrace() func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterHealth) WithFilterPath(v ...string) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterHealth) WithHeader(h map[string]string) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterHealth) WithOpaqueID(s string) func(*ClusterHealthRequest) { - return func(r *ClusterHealthRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.pending_tasks.go b/opensearchapi/api.cluster.pending_tasks.go deleted file mode 100644 index 40040655c..000000000 --- a/opensearchapi/api.cluster.pending_tasks.go +++ /dev/null @@ -1,247 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newClusterPendingTasksFunc(t Transport) ClusterPendingTasks { - return func(o ...func(*ClusterPendingTasksRequest)) (*Response, error) { - var r = ClusterPendingTasksRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterPendingTasks returns a list of any cluster-level changes (e.g. create index, update mapping, -// allocate or fail shard) which have not yet been executed. -// -// -type ClusterPendingTasks func(o ...func(*ClusterPendingTasksRequest)) (*Response, error) - -// ClusterPendingTasksRequest configures the Cluster Pending Tasks API request. -// -type ClusterPendingTasksRequest struct { - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterPendingTasksRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_cluster/pending_tasks")) - path.WriteString("/_cluster/pending_tasks") - - params = make(map[string]string) - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterPendingTasks) WithContext(v context.Context) func(*ClusterPendingTasksRequest) { - return func(r *ClusterPendingTasksRequest) { - r.ctx = v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f ClusterPendingTasks) WithLocal(v bool) func(*ClusterPendingTasksRequest) { - return func(r *ClusterPendingTasksRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f ClusterPendingTasks) WithMasterTimeout(v time.Duration) func(*ClusterPendingTasksRequest) { - return func(r *ClusterPendingTasksRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f ClusterPendingTasks) WithClusterManagerTimeout(v time.Duration) func(*ClusterPendingTasksRequest) { - return func(r *ClusterPendingTasksRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterPendingTasks) WithPretty() func(*ClusterPendingTasksRequest) { - return func(r *ClusterPendingTasksRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterPendingTasks) WithHuman() func(*ClusterPendingTasksRequest) { - return func(r *ClusterPendingTasksRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterPendingTasks) WithErrorTrace() func(*ClusterPendingTasksRequest) { - return func(r *ClusterPendingTasksRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterPendingTasks) WithFilterPath(v ...string) func(*ClusterPendingTasksRequest) { - return func(r *ClusterPendingTasksRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterPendingTasks) WithHeader(h map[string]string) func(*ClusterPendingTasksRequest) { - return func(r *ClusterPendingTasksRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterPendingTasks) WithOpaqueID(s string) func(*ClusterPendingTasksRequest) { - return func(r *ClusterPendingTasksRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.post_voting_config_exclusions.go b/opensearchapi/api.cluster.post_voting_config_exclusions.go deleted file mode 100644 index dcc341bd2..000000000 --- a/opensearchapi/api.cluster.post_voting_config_exclusions.go +++ /dev/null @@ -1,243 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newClusterPostVotingConfigExclusionsFunc(t Transport) ClusterPostVotingConfigExclusions { - return func(o ...func(*ClusterPostVotingConfigExclusionsRequest)) (*Response, error) { - var r = ClusterPostVotingConfigExclusionsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterPostVotingConfigExclusions updates the cluster voting config exclusions by node ids or node names. -// -// -type ClusterPostVotingConfigExclusions func(o ...func(*ClusterPostVotingConfigExclusionsRequest)) (*Response, error) - -// ClusterPostVotingConfigExclusionsRequest configures the Cluster Post Voting Config Exclusions API request. -// -type ClusterPostVotingConfigExclusionsRequest struct { - NodeIds string - NodeNames string - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterPostVotingConfigExclusionsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(len("/_cluster/voting_config_exclusions")) - path.WriteString("/_cluster/voting_config_exclusions") - - params = make(map[string]string) - - if r.NodeIds != "" { - params["node_ids"] = r.NodeIds - } - - if r.NodeNames != "" { - params["node_names"] = r.NodeNames - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterPostVotingConfigExclusions) WithContext(v context.Context) func(*ClusterPostVotingConfigExclusionsRequest) { - return func(r *ClusterPostVotingConfigExclusionsRequest) { - r.ctx = v - } -} - -// WithNodeIds - a list of the persistent ids of the nodes to exclude from the voting configuration. if specified, you may not also specify ?node_names.. -// -func (f ClusterPostVotingConfigExclusions) WithNodeIds(v string) func(*ClusterPostVotingConfigExclusionsRequest) { - return func(r *ClusterPostVotingConfigExclusionsRequest) { - r.NodeIds = v - } -} - -// WithNodeNames - a list of the names of the nodes to exclude from the voting configuration. if specified, you may not also specify ?node_ids.. -// -func (f ClusterPostVotingConfigExclusions) WithNodeNames(v string) func(*ClusterPostVotingConfigExclusionsRequest) { - return func(r *ClusterPostVotingConfigExclusionsRequest) { - r.NodeNames = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f ClusterPostVotingConfigExclusions) WithTimeout(v time.Duration) func(*ClusterPostVotingConfigExclusionsRequest) { - return func(r *ClusterPostVotingConfigExclusionsRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterPostVotingConfigExclusions) WithPretty() func(*ClusterPostVotingConfigExclusionsRequest) { - return func(r *ClusterPostVotingConfigExclusionsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterPostVotingConfigExclusions) WithHuman() func(*ClusterPostVotingConfigExclusionsRequest) { - return func(r *ClusterPostVotingConfigExclusionsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterPostVotingConfigExclusions) WithErrorTrace() func(*ClusterPostVotingConfigExclusionsRequest) { - return func(r *ClusterPostVotingConfigExclusionsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterPostVotingConfigExclusions) WithFilterPath(v ...string) func(*ClusterPostVotingConfigExclusionsRequest) { - return func(r *ClusterPostVotingConfigExclusionsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterPostVotingConfigExclusions) WithHeader(h map[string]string) func(*ClusterPostVotingConfigExclusionsRequest) { - return func(r *ClusterPostVotingConfigExclusionsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterPostVotingConfigExclusions) WithOpaqueID(s string) func(*ClusterPostVotingConfigExclusionsRequest) { - return func(r *ClusterPostVotingConfigExclusionsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.put_component_template.go b/opensearchapi/api.cluster.put_component_template.go deleted file mode 100644 index 1b003d641..000000000 --- a/opensearchapi/api.cluster.put_component_template.go +++ /dev/null @@ -1,271 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newClusterPutComponentTemplateFunc(t Transport) ClusterPutComponentTemplate { - return func(name string, body io.Reader, o ...func(*ClusterPutComponentTemplateRequest)) (*Response, error) { - var r = ClusterPutComponentTemplateRequest{Name: name, Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterPutComponentTemplate creates or updates a component template -// -// -type ClusterPutComponentTemplate func(name string, body io.Reader, o ...func(*ClusterPutComponentTemplateRequest)) (*Response, error) - -// ClusterPutComponentTemplateRequest configures the Cluster Put Component Template API request. -// -type ClusterPutComponentTemplateRequest struct { - Body io.Reader - - Name string - - Create *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterPutComponentTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len("_component_template") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_component_template") - path.WriteString("/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.Create != nil { - params["create"] = strconv.FormatBool(*r.Create) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterPutComponentTemplate) WithContext(v context.Context) func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - r.ctx = v - } -} - -// WithCreate - whether the index template should only be added if new or can also replace an existing one. -// -func (f ClusterPutComponentTemplate) WithCreate(v bool) func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - r.Create = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f ClusterPutComponentTemplate) WithMasterTimeout(v time.Duration) func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f ClusterPutComponentTemplate) WithClusterManagerTimeout(v time.Duration) func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f ClusterPutComponentTemplate) WithTimeout(v time.Duration) func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterPutComponentTemplate) WithPretty() func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterPutComponentTemplate) WithHuman() func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterPutComponentTemplate) WithErrorTrace() func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterPutComponentTemplate) WithFilterPath(v ...string) func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterPutComponentTemplate) WithHeader(h map[string]string) func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterPutComponentTemplate) WithOpaqueID(s string) func(*ClusterPutComponentTemplateRequest) { - return func(r *ClusterPutComponentTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.put_settings.go b/opensearchapi/api.cluster.put_settings.go deleted file mode 100644 index ed01b6f0c..000000000 --- a/opensearchapi/api.cluster.put_settings.go +++ /dev/null @@ -1,266 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newClusterPutSettingsFunc(t Transport) ClusterPutSettings { - return func(body io.Reader, o ...func(*ClusterPutSettingsRequest)) (*Response, error) { - var r = ClusterPutSettingsRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterPutSettings updates the cluster settings. -// -// -type ClusterPutSettings func(body io.Reader, o ...func(*ClusterPutSettingsRequest)) (*Response, error) - -// ClusterPutSettingsRequest configures the Cluster Put Settings API request. -// -type ClusterPutSettingsRequest struct { - Body io.Reader - - FlatSettings *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterPutSettingsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(len("/_cluster/settings")) - path.WriteString("/_cluster/settings") - - params = make(map[string]string) - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterPutSettings) WithContext(v context.Context) func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - r.ctx = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f ClusterPutSettings) WithFlatSettings(v bool) func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - r.FlatSettings = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f ClusterPutSettings) WithMasterTimeout(v time.Duration) func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f ClusterPutSettings) WithClusterManagerTimeout(v time.Duration) func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f ClusterPutSettings) WithTimeout(v time.Duration) func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterPutSettings) WithPretty() func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterPutSettings) WithHuman() func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterPutSettings) WithErrorTrace() func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterPutSettings) WithFilterPath(v ...string) func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterPutSettings) WithHeader(h map[string]string) func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterPutSettings) WithOpaqueID(s string) func(*ClusterPutSettingsRequest) { - return func(r *ClusterPutSettingsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.remote_info.go b/opensearchapi/api.cluster.remote_info.go deleted file mode 100644 index 5e1fc95d6..000000000 --- a/opensearchapi/api.cluster.remote_info.go +++ /dev/null @@ -1,202 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" -) - -func newClusterRemoteInfoFunc(t Transport) ClusterRemoteInfo { - return func(o ...func(*ClusterRemoteInfoRequest)) (*Response, error) { - var r = ClusterRemoteInfoRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterRemoteInfo returns the information about configured remote clusters. -// -// -type ClusterRemoteInfo func(o ...func(*ClusterRemoteInfoRequest)) (*Response, error) - -// ClusterRemoteInfoRequest configures the Cluster Remote Info API request. -// -type ClusterRemoteInfoRequest struct { - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterRemoteInfoRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_remote/info")) - path.WriteString("/_remote/info") - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterRemoteInfo) WithContext(v context.Context) func(*ClusterRemoteInfoRequest) { - return func(r *ClusterRemoteInfoRequest) { - r.ctx = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterRemoteInfo) WithPretty() func(*ClusterRemoteInfoRequest) { - return func(r *ClusterRemoteInfoRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterRemoteInfo) WithHuman() func(*ClusterRemoteInfoRequest) { - return func(r *ClusterRemoteInfoRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterRemoteInfo) WithErrorTrace() func(*ClusterRemoteInfoRequest) { - return func(r *ClusterRemoteInfoRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterRemoteInfo) WithFilterPath(v ...string) func(*ClusterRemoteInfoRequest) { - return func(r *ClusterRemoteInfoRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterRemoteInfo) WithHeader(h map[string]string) func(*ClusterRemoteInfoRequest) { - return func(r *ClusterRemoteInfoRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterRemoteInfo) WithOpaqueID(s string) func(*ClusterRemoteInfoRequest) { - return func(r *ClusterRemoteInfoRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.reroute.go b/opensearchapi/api.cluster.reroute.go deleted file mode 100644 index a0f3d1b82..000000000 --- a/opensearchapi/api.cluster.reroute.go +++ /dev/null @@ -1,313 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newClusterRerouteFunc(t Transport) ClusterReroute { - return func(o ...func(*ClusterRerouteRequest)) (*Response, error) { - var r = ClusterRerouteRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterReroute allows to manually change the allocation of individual shards in the cluster. -// -// -type ClusterReroute func(o ...func(*ClusterRerouteRequest)) (*Response, error) - -// ClusterRerouteRequest configures the Cluster Reroute API request. -// -type ClusterRerouteRequest struct { - Body io.Reader - - DryRun *bool - Explain *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Metric []string - RetryFailed *bool - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterRerouteRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(len("/_cluster/reroute")) - path.WriteString("/_cluster/reroute") - - params = make(map[string]string) - - if r.DryRun != nil { - params["dry_run"] = strconv.FormatBool(*r.DryRun) - } - - if r.Explain != nil { - params["explain"] = strconv.FormatBool(*r.Explain) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if len(r.Metric) > 0 { - params["metric"] = strings.Join(r.Metric, ",") - } - - if r.RetryFailed != nil { - params["retry_failed"] = strconv.FormatBool(*r.RetryFailed) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterReroute) WithContext(v context.Context) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.ctx = v - } -} - -// WithBody - The definition of `commands` to perform (`move`, `cancel`, `allocate`). -// -func (f ClusterReroute) WithBody(v io.Reader) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.Body = v - } -} - -// WithDryRun - simulate the operation only and return the resulting state. -// -func (f ClusterReroute) WithDryRun(v bool) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.DryRun = &v - } -} - -// WithExplain - return an explanation of why the commands can or cannot be executed. -// -func (f ClusterReroute) WithExplain(v bool) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.Explain = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f ClusterReroute) WithMasterTimeout(v time.Duration) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f ClusterReroute) WithClusterManagerTimeout(v time.Duration) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithMetric - limit the information returned to the specified metrics. defaults to all but metadata. -// -func (f ClusterReroute) WithMetric(v ...string) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.Metric = v - } -} - -// WithRetryFailed - retries allocation of shards that are blocked due to too many subsequent allocation failures. -// -func (f ClusterReroute) WithRetryFailed(v bool) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.RetryFailed = &v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f ClusterReroute) WithTimeout(v time.Duration) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterReroute) WithPretty() func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterReroute) WithHuman() func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterReroute) WithErrorTrace() func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterReroute) WithFilterPath(v ...string) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterReroute) WithHeader(h map[string]string) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterReroute) WithOpaqueID(s string) func(*ClusterRerouteRequest) { - return func(r *ClusterRerouteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.state.go b/opensearchapi/api.cluster.state.go deleted file mode 100644 index 520a90157..000000000 --- a/opensearchapi/api.cluster.state.go +++ /dev/null @@ -1,355 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newClusterStateFunc(t Transport) ClusterState { - return func(o ...func(*ClusterStateRequest)) (*Response, error) { - var r = ClusterStateRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterState returns a comprehensive information about the state of the cluster. -// -// -type ClusterState func(o ...func(*ClusterStateRequest)) (*Response, error) - -// ClusterStateRequest configures the Cluster State API request. -// -type ClusterStateRequest struct { - Index []string - - Metric []string - - AllowNoIndices *bool - ExpandWildcards string - FlatSettings *bool - IgnoreUnavailable *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - WaitForMetadataVersion *int - WaitForTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterStateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cluster") + 1 + len("state") + 1 + len(strings.Join(r.Metric, ",")) + 1 + len(strings.Join(r.Index, ","))) - path.WriteString("/") - path.WriteString("_cluster") - path.WriteString("/") - path.WriteString("state") - if len(r.Metric) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Metric, ",")) - } - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.WaitForMetadataVersion != nil { - params["wait_for_metadata_version"] = strconv.FormatInt(int64(*r.WaitForMetadataVersion), 10) - } - - if r.WaitForTimeout != 0 { - params["wait_for_timeout"] = formatDuration(r.WaitForTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterState) WithContext(v context.Context) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f ClusterState) WithIndex(v ...string) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.Index = v - } -} - -// WithMetric - limit the information returned to the specified metrics. -// -func (f ClusterState) WithMetric(v ...string) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.Metric = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f ClusterState) WithAllowNoIndices(v bool) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f ClusterState) WithExpandWildcards(v string) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.ExpandWildcards = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f ClusterState) WithFlatSettings(v bool) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.FlatSettings = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f ClusterState) WithIgnoreUnavailable(v bool) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f ClusterState) WithLocal(v bool) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f ClusterState) WithMasterTimeout(v time.Duration) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f ClusterState) WithClusterManagerTimeout(v time.Duration) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithWaitForMetadataVersion - wait for the metadata version to be equal or greater than the specified metadata version. -// -func (f ClusterState) WithWaitForMetadataVersion(v int) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.WaitForMetadataVersion = &v - } -} - -// WithWaitForTimeout - the maximum time to wait for wait_for_metadata_version before timing out. -// -func (f ClusterState) WithWaitForTimeout(v time.Duration) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.WaitForTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterState) WithPretty() func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterState) WithHuman() func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterState) WithErrorTrace() func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterState) WithFilterPath(v ...string) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterState) WithHeader(h map[string]string) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterState) WithOpaqueID(s string) func(*ClusterStateRequest) { - return func(r *ClusterStateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.cluster.stats.go b/opensearchapi/api.cluster.stats.go deleted file mode 100644 index f76d38ff7..000000000 --- a/opensearchapi/api.cluster.stats.go +++ /dev/null @@ -1,250 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newClusterStatsFunc(t Transport) ClusterStats { - return func(o ...func(*ClusterStatsRequest)) (*Response, error) { - var r = ClusterStatsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ClusterStats returns high-level overview of cluster statistics. -// -// -type ClusterStats func(o ...func(*ClusterStatsRequest)) (*Response, error) - -// ClusterStatsRequest configures the Cluster Stats API request. -// -type ClusterStatsRequest struct { - NodeID []string - - FlatSettings *bool - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ClusterStatsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/nodes/_cluster/stats/nodes/") + len(strings.Join(r.NodeID, ","))) - path.WriteString("/") - path.WriteString("_cluster") - path.WriteString("/") - path.WriteString("stats") - if len(r.NodeID) > 0 { - path.WriteString("/") - path.WriteString("nodes") - path.WriteString("/") - path.WriteString(strings.Join(r.NodeID, ",")) - } - - params = make(map[string]string) - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ClusterStats) WithContext(v context.Context) func(*ClusterStatsRequest) { - return func(r *ClusterStatsRequest) { - r.ctx = v - } -} - -// WithNodeID - a list of node ids or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes. -// -func (f ClusterStats) WithNodeID(v ...string) func(*ClusterStatsRequest) { - return func(r *ClusterStatsRequest) { - r.NodeID = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f ClusterStats) WithFlatSettings(v bool) func(*ClusterStatsRequest) { - return func(r *ClusterStatsRequest) { - r.FlatSettings = &v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f ClusterStats) WithTimeout(v time.Duration) func(*ClusterStatsRequest) { - return func(r *ClusterStatsRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ClusterStats) WithPretty() func(*ClusterStatsRequest) { - return func(r *ClusterStatsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ClusterStats) WithHuman() func(*ClusterStatsRequest) { - return func(r *ClusterStatsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ClusterStats) WithErrorTrace() func(*ClusterStatsRequest) { - return func(r *ClusterStatsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ClusterStats) WithFilterPath(v ...string) func(*ClusterStatsRequest) { - return func(r *ClusterStatsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ClusterStats) WithHeader(h map[string]string) func(*ClusterStatsRequest) { - return func(r *ClusterStatsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ClusterStats) WithOpaqueID(s string) func(*ClusterStatsRequest) { - return func(r *ClusterStatsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.count.go b/opensearchapi/api.count.go deleted file mode 100644 index b38aff0c3..000000000 --- a/opensearchapi/api.count.go +++ /dev/null @@ -1,416 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newCountFunc(t Transport) Count { - return func(o ...func(*CountRequest)) (*Response, error) { - var r = CountRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Count returns number of documents matching a query. -// -// -type Count func(o ...func(*CountRequest)) (*Response, error) - -// CountRequest configures the Count API request. -// -type CountRequest struct { - Index []string - - Body io.Reader - - AllowNoIndices *bool - Analyzer string - AnalyzeWildcard *bool - DefaultOperator string - Df string - ExpandWildcards string - IgnoreThrottled *bool - IgnoreUnavailable *bool - Lenient *bool - MinScore *int - Preference string - Query string - Routing []string - TerminateAfter *int - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CountRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_count")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_count") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.Analyzer != "" { - params["analyzer"] = r.Analyzer - } - - if r.AnalyzeWildcard != nil { - params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) - } - - if r.DefaultOperator != "" { - params["default_operator"] = r.DefaultOperator - } - - if r.Df != "" { - params["df"] = r.Df - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreThrottled != nil { - params["ignore_throttled"] = strconv.FormatBool(*r.IgnoreThrottled) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Lenient != nil { - params["lenient"] = strconv.FormatBool(*r.Lenient) - } - - if r.MinScore != nil { - params["min_score"] = strconv.FormatInt(int64(*r.MinScore), 10) - } - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Query != "" { - params["q"] = r.Query - } - - if len(r.Routing) > 0 { - params["routing"] = strings.Join(r.Routing, ",") - } - - if r.TerminateAfter != nil { - params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Count) WithContext(v context.Context) func(*CountRequest) { - return func(r *CountRequest) { - r.ctx = v - } -} - -// WithBody - A query to restrict the results specified with the Query DSL (optional). -// -func (f Count) WithBody(v io.Reader) func(*CountRequest) { - return func(r *CountRequest) { - r.Body = v - } -} - -// WithIndex - a list of indices to restrict the results. -// -func (f Count) WithIndex(v ...string) func(*CountRequest) { - return func(r *CountRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f Count) WithAllowNoIndices(v bool) func(*CountRequest) { - return func(r *CountRequest) { - r.AllowNoIndices = &v - } -} - -// WithAnalyzer - the analyzer to use for the query string. -// -func (f Count) WithAnalyzer(v string) func(*CountRequest) { - return func(r *CountRequest) { - r.Analyzer = v - } -} - -// WithAnalyzeWildcard - specify whether wildcard and prefix queries should be analyzed (default: false). -// -func (f Count) WithAnalyzeWildcard(v bool) func(*CountRequest) { - return func(r *CountRequest) { - r.AnalyzeWildcard = &v - } -} - -// WithDefaultOperator - the default operator for query string query (and or or). -// -func (f Count) WithDefaultOperator(v string) func(*CountRequest) { - return func(r *CountRequest) { - r.DefaultOperator = v - } -} - -// WithDf - the field to use as default where no field prefix is given in the query string. -// -func (f Count) WithDf(v string) func(*CountRequest) { - return func(r *CountRequest) { - r.Df = v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f Count) WithExpandWildcards(v string) func(*CountRequest) { - return func(r *CountRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreThrottled - whether specified concrete, expanded or aliased indices should be ignored when throttled. -// -func (f Count) WithIgnoreThrottled(v bool) func(*CountRequest) { - return func(r *CountRequest) { - r.IgnoreThrottled = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f Count) WithIgnoreUnavailable(v bool) func(*CountRequest) { - return func(r *CountRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithLenient - specify whether format-based query failures (such as providing text to a numeric field) should be ignored. -// -func (f Count) WithLenient(v bool) func(*CountRequest) { - return func(r *CountRequest) { - r.Lenient = &v - } -} - -// WithMinScore - include only documents with a specific `_score` value in the result. -// -func (f Count) WithMinScore(v int) func(*CountRequest) { - return func(r *CountRequest) { - r.MinScore = &v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f Count) WithPreference(v string) func(*CountRequest) { - return func(r *CountRequest) { - r.Preference = v - } -} - -// WithQuery - query in the lucene query string syntax. -// -func (f Count) WithQuery(v string) func(*CountRequest) { - return func(r *CountRequest) { - r.Query = v - } -} - -// WithRouting - a list of specific routing values. -// -func (f Count) WithRouting(v ...string) func(*CountRequest) { - return func(r *CountRequest) { - r.Routing = v - } -} - -// WithTerminateAfter - the maximum count for each shard, upon reaching which the query execution will terminate early. -// -func (f Count) WithTerminateAfter(v int) func(*CountRequest) { - return func(r *CountRequest) { - r.TerminateAfter = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Count) WithPretty() func(*CountRequest) { - return func(r *CountRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Count) WithHuman() func(*CountRequest) { - return func(r *CountRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Count) WithErrorTrace() func(*CountRequest) { - return func(r *CountRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Count) WithFilterPath(v ...string) func(*CountRequest) { - return func(r *CountRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Count) WithHeader(h map[string]string) func(*CountRequest) { - return func(r *CountRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Count) WithOpaqueID(s string) func(*CountRequest) { - return func(r *CountRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.create.go b/opensearchapi/api.create.go deleted file mode 100644 index f86efa953..000000000 --- a/opensearchapi/api.create.go +++ /dev/null @@ -1,313 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newCreateFunc(t Transport) Create { - return func(index string, id string, body io.Reader, o ...func(*CreateRequest)) (*Response, error) { - var r = CreateRequest{Index: index, DocumentID: id, Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Create creates a new document in the index. -// -// Returns a 409 response when a document with a same ID already exists in the index. -// -// -type Create func(index string, id string, body io.Reader, o ...func(*CreateRequest)) (*Response, error) - -// CreateRequest configures the Create API request. -// -type CreateRequest struct { - Index string - DocumentID string - - Body io.Reader - - Pipeline string - Refresh string - Routing string - Timeout time.Duration - Version *int - VersionType string - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r CreateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len(r.Index) + 1 + len(r.DocumentID) + 1 + len("_create")) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_create") - path.WriteString("/") - path.WriteString(r.DocumentID) - - params = make(map[string]string) - - if r.Pipeline != "" { - params["pipeline"] = r.Pipeline - } - - if r.Refresh != "" { - params["refresh"] = r.Refresh - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Version != nil { - params["version"] = strconv.FormatInt(int64(*r.Version), 10) - } - - if r.VersionType != "" { - params["version_type"] = r.VersionType - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Create) WithContext(v context.Context) func(*CreateRequest) { - return func(r *CreateRequest) { - r.ctx = v - } -} - -// WithPipeline - the pipeline ID to preprocess incoming documents with. -// -func (f Create) WithPipeline(v string) func(*CreateRequest) { - return func(r *CreateRequest) { - r.Pipeline = v - } -} - -// WithRefresh - if `true` then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes.. -// -func (f Create) WithRefresh(v string) func(*CreateRequest) { - return func(r *CreateRequest) { - r.Refresh = v - } -} - -// WithRouting - specific routing value. -// -func (f Create) WithRouting(v string) func(*CreateRequest) { - return func(r *CreateRequest) { - r.Routing = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f Create) WithTimeout(v time.Duration) func(*CreateRequest) { - return func(r *CreateRequest) { - r.Timeout = v - } -} - -// WithVersion - explicit version number for concurrency control. -// -func (f Create) WithVersion(v int) func(*CreateRequest) { - return func(r *CreateRequest) { - r.Version = &v - } -} - -// WithVersionType - specific version type. -// -func (f Create) WithVersionType(v string) func(*CreateRequest) { - return func(r *CreateRequest) { - r.VersionType = v - } -} - -// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the index operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1). -// -func (f Create) WithWaitForActiveShards(v string) func(*CreateRequest) { - return func(r *CreateRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Create) WithPretty() func(*CreateRequest) { - return func(r *CreateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Create) WithHuman() func(*CreateRequest) { - return func(r *CreateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Create) WithErrorTrace() func(*CreateRequest) { - return func(r *CreateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Create) WithFilterPath(v ...string) func(*CreateRequest) { - return func(r *CreateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Create) WithHeader(h map[string]string) func(*CreateRequest) { - return func(r *CreateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Create) WithOpaqueID(s string) func(*CreateRequest) { - return func(r *CreateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.dangling_indices.delete_dangling_index.go b/opensearchapi/api.dangling_indices.delete_dangling_index.go deleted file mode 100644 index c5c5ee11f..000000000 --- a/opensearchapi/api.dangling_indices.delete_dangling_index.go +++ /dev/null @@ -1,264 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newDanglingIndicesDeleteDanglingIndexFunc(t Transport) DanglingIndicesDeleteDanglingIndex { - return func(index_uuid string, o ...func(*DanglingIndicesDeleteDanglingIndexRequest)) (*Response, error) { - var r = DanglingIndicesDeleteDanglingIndexRequest{IndexUUID: index_uuid} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// DanglingIndicesDeleteDanglingIndex deletes the specified dangling index -// -// -type DanglingIndicesDeleteDanglingIndex func(index_uuid string, o ...func(*DanglingIndicesDeleteDanglingIndexRequest)) (*Response, error) - -// DanglingIndicesDeleteDanglingIndexRequest configures the Dangling Indices Delete Dangling Index API request. -// -type DanglingIndicesDeleteDanglingIndexRequest struct { - IndexUUID string - - AcceptDataLoss *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r DanglingIndicesDeleteDanglingIndexRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len("_dangling") + 1 + len(r.IndexUUID)) - path.WriteString("/") - path.WriteString("_dangling") - path.WriteString("/") - path.WriteString(r.IndexUUID) - - params = make(map[string]string) - - if r.AcceptDataLoss != nil { - params["accept_data_loss"] = strconv.FormatBool(*r.AcceptDataLoss) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f DanglingIndicesDeleteDanglingIndex) WithContext(v context.Context) func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - r.ctx = v - } -} - -// WithAcceptDataLoss - must be set to true in order to delete the dangling index. -// -func (f DanglingIndicesDeleteDanglingIndex) WithAcceptDataLoss(v bool) func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - r.AcceptDataLoss = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f DanglingIndicesDeleteDanglingIndex) WithMasterTimeout(v time.Duration) func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f DanglingIndicesDeleteDanglingIndex) WithClusterManagerTimeout(v time.Duration) func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f DanglingIndicesDeleteDanglingIndex) WithTimeout(v time.Duration) func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f DanglingIndicesDeleteDanglingIndex) WithPretty() func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f DanglingIndicesDeleteDanglingIndex) WithHuman() func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f DanglingIndicesDeleteDanglingIndex) WithErrorTrace() func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f DanglingIndicesDeleteDanglingIndex) WithFilterPath(v ...string) func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f DanglingIndicesDeleteDanglingIndex) WithHeader(h map[string]string) func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f DanglingIndicesDeleteDanglingIndex) WithOpaqueID(s string) func(*DanglingIndicesDeleteDanglingIndexRequest) { - return func(r *DanglingIndicesDeleteDanglingIndexRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.dangling_indices.import_dangling_index.go b/opensearchapi/api.dangling_indices.import_dangling_index.go deleted file mode 100644 index a7cba7dba..000000000 --- a/opensearchapi/api.dangling_indices.import_dangling_index.go +++ /dev/null @@ -1,264 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newDanglingIndicesImportDanglingIndexFunc(t Transport) DanglingIndicesImportDanglingIndex { - return func(index_uuid string, o ...func(*DanglingIndicesImportDanglingIndexRequest)) (*Response, error) { - var r = DanglingIndicesImportDanglingIndexRequest{IndexUUID: index_uuid} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// DanglingIndicesImportDanglingIndex imports the specified dangling index -// -// -type DanglingIndicesImportDanglingIndex func(index_uuid string, o ...func(*DanglingIndicesImportDanglingIndexRequest)) (*Response, error) - -// DanglingIndicesImportDanglingIndexRequest configures the Dangling Indices Import Dangling Index API request. -// -type DanglingIndicesImportDanglingIndexRequest struct { - IndexUUID string - - AcceptDataLoss *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r DanglingIndicesImportDanglingIndexRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_dangling") + 1 + len(r.IndexUUID)) - path.WriteString("/") - path.WriteString("_dangling") - path.WriteString("/") - path.WriteString(r.IndexUUID) - - params = make(map[string]string) - - if r.AcceptDataLoss != nil { - params["accept_data_loss"] = strconv.FormatBool(*r.AcceptDataLoss) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f DanglingIndicesImportDanglingIndex) WithContext(v context.Context) func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - r.ctx = v - } -} - -// WithAcceptDataLoss - must be set to true in order to import the dangling index. -// -func (f DanglingIndicesImportDanglingIndex) WithAcceptDataLoss(v bool) func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - r.AcceptDataLoss = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f DanglingIndicesImportDanglingIndex) WithMasterTimeout(v time.Duration) func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f DanglingIndicesImportDanglingIndex) WithClusterManagerTimeout(v time.Duration) func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f DanglingIndicesImportDanglingIndex) WithTimeout(v time.Duration) func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f DanglingIndicesImportDanglingIndex) WithPretty() func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f DanglingIndicesImportDanglingIndex) WithHuman() func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f DanglingIndicesImportDanglingIndex) WithErrorTrace() func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f DanglingIndicesImportDanglingIndex) WithFilterPath(v ...string) func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f DanglingIndicesImportDanglingIndex) WithHeader(h map[string]string) func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f DanglingIndicesImportDanglingIndex) WithOpaqueID(s string) func(*DanglingIndicesImportDanglingIndexRequest) { - return func(r *DanglingIndicesImportDanglingIndexRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.dangling_indices.list_dangling_indices.go b/opensearchapi/api.dangling_indices.list_dangling_indices.go deleted file mode 100644 index f54af68fd..000000000 --- a/opensearchapi/api.dangling_indices.list_dangling_indices.go +++ /dev/null @@ -1,202 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" -) - -func newDanglingIndicesListDanglingIndicesFunc(t Transport) DanglingIndicesListDanglingIndices { - return func(o ...func(*DanglingIndicesListDanglingIndicesRequest)) (*Response, error) { - var r = DanglingIndicesListDanglingIndicesRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// DanglingIndicesListDanglingIndices returns all dangling indices. -// -// -type DanglingIndicesListDanglingIndices func(o ...func(*DanglingIndicesListDanglingIndicesRequest)) (*Response, error) - -// DanglingIndicesListDanglingIndicesRequest configures the Dangling Indices List Dangling Indices API request. -// -type DanglingIndicesListDanglingIndicesRequest struct { - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r DanglingIndicesListDanglingIndicesRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_dangling")) - path.WriteString("/_dangling") - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f DanglingIndicesListDanglingIndices) WithContext(v context.Context) func(*DanglingIndicesListDanglingIndicesRequest) { - return func(r *DanglingIndicesListDanglingIndicesRequest) { - r.ctx = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f DanglingIndicesListDanglingIndices) WithPretty() func(*DanglingIndicesListDanglingIndicesRequest) { - return func(r *DanglingIndicesListDanglingIndicesRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f DanglingIndicesListDanglingIndices) WithHuman() func(*DanglingIndicesListDanglingIndicesRequest) { - return func(r *DanglingIndicesListDanglingIndicesRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f DanglingIndicesListDanglingIndices) WithErrorTrace() func(*DanglingIndicesListDanglingIndicesRequest) { - return func(r *DanglingIndicesListDanglingIndicesRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f DanglingIndicesListDanglingIndices) WithFilterPath(v ...string) func(*DanglingIndicesListDanglingIndicesRequest) { - return func(r *DanglingIndicesListDanglingIndicesRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f DanglingIndicesListDanglingIndices) WithHeader(h map[string]string) func(*DanglingIndicesListDanglingIndicesRequest) { - return func(r *DanglingIndicesListDanglingIndicesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f DanglingIndicesListDanglingIndices) WithOpaqueID(s string) func(*DanglingIndicesListDanglingIndicesRequest) { - return func(r *DanglingIndicesListDanglingIndicesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.delete.go b/opensearchapi/api.delete.go deleted file mode 100644 index f26445348..000000000 --- a/opensearchapi/api.delete.go +++ /dev/null @@ -1,316 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newDeleteFunc(t Transport) Delete { - return func(index string, id string, o ...func(*DeleteRequest)) (*Response, error) { - var r = DeleteRequest{Index: index, DocumentID: id} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Delete removes a document from the index. -// -// -type Delete func(index string, id string, o ...func(*DeleteRequest)) (*Response, error) - -// DeleteRequest configures the Delete API request. -// -type DeleteRequest struct { - Index string - DocumentID string - - IfPrimaryTerm *int - IfSeqNo *int - Refresh string - Routing string - Timeout time.Duration - Version *int - VersionType string - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r DeleteRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len(r.Index) + 1 + len("_doc") + 1 + len(r.DocumentID)) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/_doc") - path.WriteString("/") - path.WriteString(r.DocumentID) - - params = make(map[string]string) - - if r.IfPrimaryTerm != nil { - params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10) - } - - if r.IfSeqNo != nil { - params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10) - } - - if r.Refresh != "" { - params["refresh"] = r.Refresh - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Version != nil { - params["version"] = strconv.FormatInt(int64(*r.Version), 10) - } - - if r.VersionType != "" { - params["version_type"] = r.VersionType - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Delete) WithContext(v context.Context) func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.ctx = v - } -} - -// WithIfPrimaryTerm - only perform the delete operation if the last operation that has changed the document has the specified primary term. -// -func (f Delete) WithIfPrimaryTerm(v int) func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.IfPrimaryTerm = &v - } -} - -// WithIfSeqNo - only perform the delete operation if the last operation that has changed the document has the specified sequence number. -// -func (f Delete) WithIfSeqNo(v int) func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.IfSeqNo = &v - } -} - -// WithRefresh - if `true` then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes.. -// -func (f Delete) WithRefresh(v string) func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.Refresh = v - } -} - -// WithRouting - specific routing value. -// -func (f Delete) WithRouting(v string) func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.Routing = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f Delete) WithTimeout(v time.Duration) func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.Timeout = v - } -} - -// WithVersion - explicit version number for concurrency control. -// -func (f Delete) WithVersion(v int) func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.Version = &v - } -} - -// WithVersionType - specific version type. -// -func (f Delete) WithVersionType(v string) func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.VersionType = v - } -} - -// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the delete operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1). -// -func (f Delete) WithWaitForActiveShards(v string) func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Delete) WithPretty() func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Delete) WithHuman() func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Delete) WithErrorTrace() func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Delete) WithFilterPath(v ...string) func(*DeleteRequest) { - return func(r *DeleteRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Delete) WithHeader(h map[string]string) func(*DeleteRequest) { - return func(r *DeleteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Delete) WithOpaqueID(s string) func(*DeleteRequest) { - return func(r *DeleteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.delete_by_query.go b/opensearchapi/api.delete_by_query.go deleted file mode 100644 index f5cb18357..000000000 --- a/opensearchapi/api.delete_by_query.go +++ /dev/null @@ -1,651 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "fmt" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newDeleteByQueryFunc(t Transport) DeleteByQuery { - return func(index []string, body io.Reader, o ...func(*DeleteByQueryRequest)) (*Response, error) { - var r = DeleteByQueryRequest{Index: index, Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// DeleteByQuery deletes documents matching the provided query. -// -// -type DeleteByQuery func(index []string, body io.Reader, o ...func(*DeleteByQueryRequest)) (*Response, error) - -// DeleteByQueryRequest configures the Delete By Query API request. -// -type DeleteByQueryRequest struct { - Index []string - - Body io.Reader - - AllowNoIndices *bool - Analyzer string - AnalyzeWildcard *bool - Conflicts string - DefaultOperator string - Df string - ExpandWildcards string - From *int - IgnoreUnavailable *bool - Lenient *bool - MaxDocs *int - Preference string - Query string - Refresh *bool - RequestCache *bool - RequestsPerSecond *int - Routing []string - Scroll time.Duration - ScrollSize *int - SearchTimeout time.Duration - SearchType string - Size *int - Slices interface{} - Sort []string - Source interface{} - SourceExcludes []string - SourceIncludes []string - Stats []string - TerminateAfter *int - Timeout time.Duration - Version *bool - WaitForActiveShards string - WaitForCompletion *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r DeleteByQueryRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_delete_by_query")) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - path.WriteString("/") - path.WriteString("_delete_by_query") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.Analyzer != "" { - params["analyzer"] = r.Analyzer - } - - if r.AnalyzeWildcard != nil { - params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) - } - - if r.Conflicts != "" { - params["conflicts"] = r.Conflicts - } - - if r.DefaultOperator != "" { - params["default_operator"] = r.DefaultOperator - } - - if r.Df != "" { - params["df"] = r.Df - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.From != nil { - params["from"] = strconv.FormatInt(int64(*r.From), 10) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Lenient != nil { - params["lenient"] = strconv.FormatBool(*r.Lenient) - } - - if r.MaxDocs != nil { - params["max_docs"] = strconv.FormatInt(int64(*r.MaxDocs), 10) - } - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Query != "" { - params["q"] = r.Query - } - - if r.Refresh != nil { - params["refresh"] = strconv.FormatBool(*r.Refresh) - } - - if r.RequestCache != nil { - params["request_cache"] = strconv.FormatBool(*r.RequestCache) - } - - if r.RequestsPerSecond != nil { - params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) - } - - if len(r.Routing) > 0 { - params["routing"] = strings.Join(r.Routing, ",") - } - - if r.Scroll != 0 { - params["scroll"] = formatDuration(r.Scroll) - } - - if r.ScrollSize != nil { - params["scroll_size"] = strconv.FormatInt(int64(*r.ScrollSize), 10) - } - - if r.SearchTimeout != 0 { - params["search_timeout"] = formatDuration(r.SearchTimeout) - } - - if r.SearchType != "" { - params["search_type"] = r.SearchType - } - - if r.Size != nil { - params["size"] = strconv.FormatInt(int64(*r.Size), 10) - } - - if r.Slices != nil { - params["slices"] = fmt.Sprintf("%v", r.Slices) - } - - if len(r.Sort) > 0 { - params["sort"] = strings.Join(r.Sort, ",") - } - - if source, ok := r.Source.(bool); ok { - params["_source"] = strconv.FormatBool(source) - } else if source, ok := r.Source.(string); ok && source != "" { - params["_source"] = source - } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { - params["_source"] = strings.Join(sources, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if len(r.Stats) > 0 { - params["stats"] = strings.Join(r.Stats, ",") - } - - if r.TerminateAfter != nil { - params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Version != nil { - params["version"] = strconv.FormatBool(*r.Version) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.WaitForCompletion != nil { - params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f DeleteByQuery) WithContext(v context.Context) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.ctx = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f DeleteByQuery) WithAllowNoIndices(v bool) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.AllowNoIndices = &v - } -} - -// WithAnalyzer - the analyzer to use for the query string. -// -func (f DeleteByQuery) WithAnalyzer(v string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Analyzer = v - } -} - -// WithAnalyzeWildcard - specify whether wildcard and prefix queries should be analyzed (default: false). -// -func (f DeleteByQuery) WithAnalyzeWildcard(v bool) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.AnalyzeWildcard = &v - } -} - -// WithConflicts - what to do when the delete by query hits version conflicts?. -// -func (f DeleteByQuery) WithConflicts(v string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Conflicts = v - } -} - -// WithDefaultOperator - the default operator for query string query (and or or). -// -func (f DeleteByQuery) WithDefaultOperator(v string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.DefaultOperator = v - } -} - -// WithDf - the field to use as default where no field prefix is given in the query string. -// -func (f DeleteByQuery) WithDf(v string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Df = v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f DeleteByQuery) WithExpandWildcards(v string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.ExpandWildcards = v - } -} - -// WithFrom - starting offset (default: 0). -// -func (f DeleteByQuery) WithFrom(v int) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.From = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f DeleteByQuery) WithIgnoreUnavailable(v bool) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithLenient - specify whether format-based query failures (such as providing text to a numeric field) should be ignored. -// -func (f DeleteByQuery) WithLenient(v bool) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Lenient = &v - } -} - -// WithMaxDocs - maximum number of documents to process (default: all documents). -// -func (f DeleteByQuery) WithMaxDocs(v int) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.MaxDocs = &v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f DeleteByQuery) WithPreference(v string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Preference = v - } -} - -// WithQuery - query in the lucene query string syntax. -// -func (f DeleteByQuery) WithQuery(v string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Query = v - } -} - -// WithRefresh - should the effected indexes be refreshed?. -// -func (f DeleteByQuery) WithRefresh(v bool) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Refresh = &v - } -} - -// WithRequestCache - specify if request cache should be used for this request or not, defaults to index level setting. -// -func (f DeleteByQuery) WithRequestCache(v bool) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.RequestCache = &v - } -} - -// WithRequestsPerSecond - the throttle for this request in sub-requests per second. -1 means no throttle.. -// -func (f DeleteByQuery) WithRequestsPerSecond(v int) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.RequestsPerSecond = &v - } -} - -// WithRouting - a list of specific routing values. -// -func (f DeleteByQuery) WithRouting(v ...string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Routing = v - } -} - -// WithScroll - specify how long a consistent view of the index should be maintained for scrolled search. -// -func (f DeleteByQuery) WithScroll(v time.Duration) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Scroll = v - } -} - -// WithScrollSize - size on the scroll request powering the delete by query. -// -func (f DeleteByQuery) WithScrollSize(v int) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.ScrollSize = &v - } -} - -// WithSearchTimeout - explicit timeout for each search request. defaults to no timeout.. -// -func (f DeleteByQuery) WithSearchTimeout(v time.Duration) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.SearchTimeout = v - } -} - -// WithSearchType - search operation type. -// -func (f DeleteByQuery) WithSearchType(v string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.SearchType = v - } -} - -// WithSize - deprecated, please use `max_docs` instead. -// -func (f DeleteByQuery) WithSize(v int) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Size = &v - } -} - -// WithSlices - the number of slices this task should be divided into. defaults to 1, meaning the task isn't sliced into subtasks. can be set to `auto`.. -// -func (f DeleteByQuery) WithSlices(v interface{}) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Slices = v - } -} - -// WithSort - a list of : pairs. -// -func (f DeleteByQuery) WithSort(v ...string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Sort = v - } -} - -// WithSource - true or false to return the _source field or not, or a list of fields to return. -// -func (f DeleteByQuery) WithSource(v interface{}) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Source = v - } -} - -// WithSourceExcludes - a list of fields to exclude from the returned _source field. -// -func (f DeleteByQuery) WithSourceExcludes(v ...string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - a list of fields to extract and return from the _source field. -// -func (f DeleteByQuery) WithSourceIncludes(v ...string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.SourceIncludes = v - } -} - -// WithStats - specific 'tag' of the request for logging and statistical purposes. -// -func (f DeleteByQuery) WithStats(v ...string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Stats = v - } -} - -// WithTerminateAfter - the maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early.. -// -func (f DeleteByQuery) WithTerminateAfter(v int) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.TerminateAfter = &v - } -} - -// WithTimeout - time each individual bulk request should wait for shards that are unavailable.. -// -func (f DeleteByQuery) WithTimeout(v time.Duration) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Timeout = v - } -} - -// WithVersion - specify whether to return document version as part of a hit. -// -func (f DeleteByQuery) WithVersion(v bool) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Version = &v - } -} - -// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the delete by query operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1). -// -func (f DeleteByQuery) WithWaitForActiveShards(v string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.WaitForActiveShards = v - } -} - -// WithWaitForCompletion - should the request should block until the delete by query is complete.. -// -func (f DeleteByQuery) WithWaitForCompletion(v bool) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.WaitForCompletion = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f DeleteByQuery) WithPretty() func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f DeleteByQuery) WithHuman() func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f DeleteByQuery) WithErrorTrace() func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f DeleteByQuery) WithFilterPath(v ...string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f DeleteByQuery) WithHeader(h map[string]string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f DeleteByQuery) WithOpaqueID(s string) func(*DeleteByQueryRequest) { - return func(r *DeleteByQueryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.delete_by_query_rethrottle.go b/opensearchapi/api.delete_by_query_rethrottle.go deleted file mode 100644 index 63f98866e..000000000 --- a/opensearchapi/api.delete_by_query_rethrottle.go +++ /dev/null @@ -1,224 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newDeleteByQueryRethrottleFunc(t Transport) DeleteByQueryRethrottle { - return func(task_id string, requests_per_second *int, o ...func(*DeleteByQueryRethrottleRequest)) (*Response, error) { - var r = DeleteByQueryRethrottleRequest{TaskID: task_id, RequestsPerSecond: requests_per_second} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// DeleteByQueryRethrottle changes the number of requests per second for a particular Delete By Query operation. -// -// -type DeleteByQueryRethrottle func(task_id string, requests_per_second *int, o ...func(*DeleteByQueryRethrottleRequest)) (*Response, error) - -// DeleteByQueryRethrottleRequest configures the Delete By Query Rethrottle API request. -// -type DeleteByQueryRethrottleRequest struct { - TaskID string - - RequestsPerSecond *int - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r DeleteByQueryRethrottleRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_delete_by_query") + 1 + len(r.TaskID) + 1 + len("_rethrottle")) - path.WriteString("/") - path.WriteString("_delete_by_query") - path.WriteString("/") - path.WriteString(r.TaskID) - path.WriteString("/") - path.WriteString("_rethrottle") - - params = make(map[string]string) - - if r.RequestsPerSecond != nil { - params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f DeleteByQueryRethrottle) WithContext(v context.Context) func(*DeleteByQueryRethrottleRequest) { - return func(r *DeleteByQueryRethrottleRequest) { - r.ctx = v - } -} - -// WithRequestsPerSecond - the throttle to set on this request in floating sub-requests per second. -1 means set no throttle.. -// -func (f DeleteByQueryRethrottle) WithRequestsPerSecond(v int) func(*DeleteByQueryRethrottleRequest) { - return func(r *DeleteByQueryRethrottleRequest) { - r.RequestsPerSecond = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f DeleteByQueryRethrottle) WithPretty() func(*DeleteByQueryRethrottleRequest) { - return func(r *DeleteByQueryRethrottleRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f DeleteByQueryRethrottle) WithHuman() func(*DeleteByQueryRethrottleRequest) { - return func(r *DeleteByQueryRethrottleRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f DeleteByQueryRethrottle) WithErrorTrace() func(*DeleteByQueryRethrottleRequest) { - return func(r *DeleteByQueryRethrottleRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f DeleteByQueryRethrottle) WithFilterPath(v ...string) func(*DeleteByQueryRethrottleRequest) { - return func(r *DeleteByQueryRethrottleRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f DeleteByQueryRethrottle) WithHeader(h map[string]string) func(*DeleteByQueryRethrottleRequest) { - return func(r *DeleteByQueryRethrottleRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f DeleteByQueryRethrottle) WithOpaqueID(s string) func(*DeleteByQueryRethrottleRequest) { - return func(r *DeleteByQueryRethrottleRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.delete_script.go b/opensearchapi/api.delete_script.go deleted file mode 100644 index af1a031b8..000000000 --- a/opensearchapi/api.delete_script.go +++ /dev/null @@ -1,250 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newDeleteScriptFunc(t Transport) DeleteScript { - return func(id string, o ...func(*DeleteScriptRequest)) (*Response, error) { - var r = DeleteScriptRequest{ScriptID: id} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// DeleteScript deletes a script. -// -// -type DeleteScript func(id string, o ...func(*DeleteScriptRequest)) (*Response, error) - -// DeleteScriptRequest configures the Delete Script API request. -// -type DeleteScriptRequest struct { - ScriptID string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r DeleteScriptRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len("_scripts") + 1 + len(r.ScriptID)) - path.WriteString("/") - path.WriteString("_scripts") - path.WriteString("/") - path.WriteString(r.ScriptID) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f DeleteScript) WithContext(v context.Context) func(*DeleteScriptRequest) { - return func(r *DeleteScriptRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f DeleteScript) WithMasterTimeout(v time.Duration) func(*DeleteScriptRequest) { - return func(r *DeleteScriptRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f DeleteScript) WithClusterManagerTimeout(v time.Duration) func(*DeleteScriptRequest) { - return func(r *DeleteScriptRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f DeleteScript) WithTimeout(v time.Duration) func(*DeleteScriptRequest) { - return func(r *DeleteScriptRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f DeleteScript) WithPretty() func(*DeleteScriptRequest) { - return func(r *DeleteScriptRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f DeleteScript) WithHuman() func(*DeleteScriptRequest) { - return func(r *DeleteScriptRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f DeleteScript) WithErrorTrace() func(*DeleteScriptRequest) { - return func(r *DeleteScriptRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f DeleteScript) WithFilterPath(v ...string) func(*DeleteScriptRequest) { - return func(r *DeleteScriptRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f DeleteScript) WithHeader(h map[string]string) func(*DeleteScriptRequest) { - return func(r *DeleteScriptRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f DeleteScript) WithOpaqueID(s string) func(*DeleteScriptRequest) { - return func(r *DeleteScriptRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.document_test.go b/opensearchapi/api.document_test.go deleted file mode 100644 index 1250b5a35..000000000 --- a/opensearchapi/api.document_test.go +++ /dev/null @@ -1,355 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -//go:build integration -// +build integration - -package opensearchapi_test - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "github.com/opensearch-project/opensearch-go/v2" - "github.com/opensearch-project/opensearch-go/v2/opensearchapi" - "github.com/stretchr/testify/require" - "io/ioutil" - "net/http" - "regexp" - "strings" - "testing" - "time" -) - -func TestDocumentRequest_Do(t *testing.T) { - index := fmt.Sprintf("index-%s", time.Now().Format("2006-01-02-15-04-05")) - - tests := []struct { - name string - r DataStreamRequest - want *opensearchapi.Response - wantBody string - wantErr bool - refresh bool - }{ - // Create document - { - name: "TestCreateRequest_Do", - r: opensearchapi.CreateRequest{ - Index: index, - DocumentID: "1", - Body: strings.NewReader(`{ "title": "Moneyball", "director": "Bennett Miller", "year": "2011" }`), - }, - want: &opensearchapi.Response{ - StatusCode: 201, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - "Location": []string{fmt.Sprintf("/%s/_doc/1", index)}, - }, - }, - wantBody: fmt.Sprintf(`{"_index":"%s","_id":"1","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":0,"_primary_term":1}`, index), - wantErr: false, - }, - { - name: "TestCreateRequest_Do", - r: opensearchapi.CreateRequest{ - Index: index, - DocumentID: "2", - Body: strings.NewReader(`{ "title": "Tenet", "director": "Christopher Nolan", "year": "2019" }`), - }, - want: &opensearchapi.Response{ - StatusCode: 201, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - "Location": []string{fmt.Sprintf("/%s/_doc/2", index)}, - }, - }, - wantBody: fmt.Sprintf(`{"_index":"%s","_id":"2","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":1,"_primary_term":1}`, index), - wantErr: false, - }, - - // Get document - { - name: "TestGetRequest_Do", - r: opensearchapi.GetRequest{ - Index: index, - DocumentID: "2", - Source: true, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: fmt.Sprintf(`{"_id":"2", "_index":"%s", "_primary_term":1, "_seq_no":1, "_source": {"director":"Christopher Nolan", "title":"Tenet", "year":"2019"}, "_version":1, "found":true}`, index), - wantErr: false, - }, - // Get multiple documents - { - name: "TestMultiGetRequest_Do. Source parameter is a bool and slice of strings", - r: opensearchapi.MgetRequest{ - Index: index, - Body: strings.NewReader(`{ "docs": [ { "_id": "1", "_source": true }, { "_id": "2", "_source": [ "title" ] } ] }`), - // seems to does not work - Source: false, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: fmt.Sprintf(`{ "docs": [ { "_id": "1", "_index": "%s", "_primary_term": 1, "_seq_no": 0, "_source": { "director": "Bennett Miller", "title": "Moneyball", "year": "2011" }, "_version": 1, "found": true }, { "_id": "2", "_index": "%s", "_primary_term": 1, "_seq_no": 1, "_source": {"title":"Tenet"}, "_version": 1, "found": true } ] }`, index, index), - wantErr: false, - }, - // Get source document - { - name: "TestGetSourceRequest_Do. Source parameter is a bool and slice of strings", - r: opensearchapi.GetSourceRequest{ - Index: index, - DocumentID: "2", - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: `{"director":"Christopher Nolan", "title":"Tenet", "year":"2019"}`, - wantErr: false, - }, - - // Exists document - { - name: "TestExistsRequest_Do", - r: opensearchapi.ExistsRequest{ - Index: index, - DocumentID: "2", - Source: true, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - "Content-Length": []string{"189"}, - }, - }, - wantBody: ``, - wantErr: false, - }, - - // Explain document - { - name: "TestExplainRequest_Do", - r: opensearchapi.ExplainRequest{ - Index: index, - DocumentID: "2", - Query: `title: "Tenet"`, - Source: true, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: ``, - wantErr: false, - refresh: true, - }, - - // Search document - { - name: "TestSearchRequest_Do. Source parameter is a slice of strings", - r: opensearchapi.SearchRequest{ - Index: []string{index}, - Body: strings.NewReader(`{ "query": { "match": { "title": "Tenet" } } }`), - Source: true, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: fmt.Sprintf(`{"took":0,"timed_out":false,"_shards":{"total":4,"successful":4,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":0.6931471,"hits":[{"_index":"%s","_id":"2","_score":0.6931471,"_source":{ "title": "Tenet", "director": "Christopher Nolan", "year": "2019" }}]}}`, index), - wantErr: false, - refresh: true, - }, - - // Update document - { - name: "TestUpdateRequest_Do", - r: opensearchapi.UpdateRequest{ - Index: index, - DocumentID: "1", - Body: strings.NewReader(`{ "doc": { "title": "Moneyball", "director": "Bennett", "year": "2012" } }`), - Source: nil, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: fmt.Sprintf(`{"_index":"%s","_id":"1","_version":2,"result":"updated","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":2,"_primary_term":1}`, index), - wantErr: false, - }, - { - name: "TestUpdateRequest_Do. Source parameter is bool", - r: opensearchapi.UpdateRequest{ - Index: index, - DocumentID: "1", - Body: strings.NewReader(`{ "doc": { "title": "Moneyball", "director": "Bennett", "year": "2012" } }`), - Source: true, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: fmt.Sprintf(`{"_index":"%s","_id":"1","_version":2,"result":"noop","_shards":{"total":0,"successful":0,"failed":0},"_seq_no":2,"_primary_term":1,"get":{"_seq_no":2,"_primary_term":1,"found":true,"_source":{"title":"Moneyball","director":"Bennett","year":"2012"}}}`, index), - wantErr: false, - }, - { - name: "TestUpdateRequest_Do. Source parameter is a slice of strings", - r: opensearchapi.UpdateRequest{ - Index: index, - DocumentID: "1", - Body: strings.NewReader(`{ "doc": { "title": "Moneyball", "director": "Bennett", "year": "2012" } }`), - Source: []string{"true"}, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: fmt.Sprintf(`{"_index":"%s","_id":"1","_version":2,"result":"noop","_shards":{"total":0,"successful":0,"failed":0},"_seq_no":2,"_primary_term":1,"get":{"_seq_no":2,"_primary_term":1,"found":true,"_source":{"title":"Moneyball","director":"Bennett","year":"2012"}}}`, index), - wantErr: false, - }, - { - name: "TestUpdateRequest_Do. Source Excludes", - r: opensearchapi.UpdateRequest{ - Index: index, - DocumentID: "1", - Body: strings.NewReader(`{ "doc": { "title": "Moneyball", "director": "Bennett", "year": "2012" } }`), - Source: []string{"true"}, - SourceExcludes: []string{"director"}, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: fmt.Sprintf(`{"_index":"%s","_id":"1","_version":2,"result":"noop","_shards":{"total":0,"successful":0,"failed":0},"_seq_no":2,"_primary_term":1,"get":{"_seq_no":2,"_primary_term":1,"found":true,"_source":{"title":"Moneyball","year":"2012"}}}`, index), - wantErr: false, - }, - // Update by query - { - name: "TestUpdateByQueryRequest_Do. Source Excludes", - r: opensearchapi.UpdateByQueryRequest{ - Index: []string{index}, - Query: `title: "Tenet"`, - Body: strings.NewReader(`{ "script" : { "source": "ctx._source.title += params.title", "lang": "painless", "params" : { "title" : "TeneT" } } }`), - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: `{"batches":1, "deleted":0, "failures":[], "noops":0, "requests_per_second":-1, "retries":{"bulk":0, "search":0}, "throttled_millis":0, "throttled_until_millis":0, "timed_out":false, "took":0, "total":1, "updated":1, "version_conflicts":0}`, - wantErr: false, - refresh: true, - }, - - // Bulk document - { - name: "TestBulkRequest_Do.", - r: opensearchapi.BulkRequest{ - Index: index, - Body: strings.NewReader(`{ "index": { "_index": "movies", "_id": "tt1979320" } } -{ "title": "Rush", "year": 2013 } -{ "create": { "_index": "movies", "_id": "tt1392214" } } -{ "title": "Prisoners", "year": 2013 } -{ "update": { "_index": "movies", "_id": "tt0816711" } } -{ "doc" : { "title": "World War Z" } } -`), - Source: []string{"true"}, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantErr: false, - }, - } - - client, err := opensearch.NewDefaultClient() - require.NoError(t, err) - - iCreate := opensearchapi.IndicesCreateRequest{ - Index: index, - Pretty: true, - Human: true, - ErrorTrace: true, - Body: strings.NewReader(fmt.Sprintf(`{"settings": {"index": {"number_of_shards": 4}}}`)), - } - - _, err = iCreate.Do(context.Background(), client) - require.NoError(t, err) - - for _, tt := range tests { - if tt.refresh { - refresh, err := client.Indices.Refresh() - require.NoError(t, err) - t.Logf("response: %+v", refresh) - } - - t.Run(tt.name, func(t *testing.T) { - got, err := tt.r.Do(context.Background(), client) - if (err != nil) != tt.wantErr { - t.Errorf("Do() error = %+v, wantErr %v", err, tt.wantErr) - return - } - - require.Equalf(t, tt.want.StatusCode, got.StatusCode, "Do() got = %v, want %v", got.StatusCode, tt.want.StatusCode) - - if tt.wantBody != "" { - for name, value := range tt.want.Header { - require.Contains(t, got.Header, name) - require.Equal(t, value, got.Header[name]) - } - - defer got.Body.Close() - body, err := ioutil.ReadAll(got.Body) - require.NoError(t, err) - - buffer := new(bytes.Buffer) - err = json.Compact(buffer, body) - require.NoError(t, err) - - // ignore took field, since it is dynamic - took := regexp.MustCompile(`"took":\d+`) - actual := took.ReplaceAllString(buffer.String(), `"took":0`) - // ignore _type field, since it is legacy - actual = strings.ReplaceAll(actual, `"_type":"_doc",`, "") - - require.JSONEqf(t, tt.wantBody, actual, "Do() got = %v, want %v", got.String(), tt.wantBody) - } - }) - } -} diff --git a/opensearchapi/api.exists.go b/opensearchapi/api.exists.go deleted file mode 100644 index 40aec3cc2..000000000 --- a/opensearchapi/api.exists.go +++ /dev/null @@ -1,345 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newExistsFunc(t Transport) Exists { - return func(index string, id string, o ...func(*ExistsRequest)) (*Response, error) { - var r = ExistsRequest{Index: index, DocumentID: id} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Exists returns information about whether a document exists in an index. -// -// -type Exists func(index string, id string, o ...func(*ExistsRequest)) (*Response, error) - -// ExistsRequest configures the Exists API request. -// -type ExistsRequest struct { - Index string - DocumentID string - - Preference string - Realtime *bool - Refresh *bool - Routing string - Source interface{} - SourceExcludes []string - SourceIncludes []string - StoredFields []string - Version *int - VersionType string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ExistsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "HEAD" - - path.Grow(1 + len(r.Index) + 1 + len("_doc") + 1 + len(r.DocumentID)) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/_doc") - path.WriteString("/") - path.WriteString(r.DocumentID) - - params = make(map[string]string) - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Realtime != nil { - params["realtime"] = strconv.FormatBool(*r.Realtime) - } - - if r.Refresh != nil { - params["refresh"] = strconv.FormatBool(*r.Refresh) - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if source, ok := r.Source.(bool); ok { - params["_source"] = strconv.FormatBool(source) - } else if source, ok := r.Source.(string); ok && source != "" { - params["_source"] = source - } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { - params["_source"] = strings.Join(sources, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if len(r.StoredFields) > 0 { - params["stored_fields"] = strings.Join(r.StoredFields, ",") - } - - if r.Version != nil { - params["version"] = strconv.FormatInt(int64(*r.Version), 10) - } - - if r.VersionType != "" { - params["version_type"] = r.VersionType - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Exists) WithContext(v context.Context) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.ctx = v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f Exists) WithPreference(v string) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.Preference = v - } -} - -// WithRealtime - specify whether to perform the operation in realtime or search mode. -// -func (f Exists) WithRealtime(v bool) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.Realtime = &v - } -} - -// WithRefresh - refresh the shard containing the document before performing the operation. -// -func (f Exists) WithRefresh(v bool) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.Refresh = &v - } -} - -// WithRouting - specific routing value. -// -func (f Exists) WithRouting(v string) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.Routing = v - } -} - -// WithSource - true or false to return the _source field or not, or a list of fields to return. -// -func (f Exists) WithSource(v interface{}) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.Source = v - } -} - -// WithSourceExcludes - a list of fields to exclude from the returned _source field. -// -func (f Exists) WithSourceExcludes(v ...string) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - a list of fields to extract and return from the _source field. -// -func (f Exists) WithSourceIncludes(v ...string) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.SourceIncludes = v - } -} - -// WithStoredFields - a list of stored fields to return in the response. -// -func (f Exists) WithStoredFields(v ...string) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.StoredFields = v - } -} - -// WithVersion - explicit version number for concurrency control. -// -func (f Exists) WithVersion(v int) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.Version = &v - } -} - -// WithVersionType - specific version type. -// -func (f Exists) WithVersionType(v string) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.VersionType = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Exists) WithPretty() func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Exists) WithHuman() func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Exists) WithErrorTrace() func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Exists) WithFilterPath(v ...string) func(*ExistsRequest) { - return func(r *ExistsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Exists) WithHeader(h map[string]string) func(*ExistsRequest) { - return func(r *ExistsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Exists) WithOpaqueID(s string) func(*ExistsRequest) { - return func(r *ExistsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.exists_source.go b/opensearchapi/api.exists_source.go deleted file mode 100644 index 54ce0c25e..000000000 --- a/opensearchapi/api.exists_source.go +++ /dev/null @@ -1,333 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newExistsSourceFunc(t Transport) ExistsSource { - return func(index string, id string, o ...func(*ExistsSourceRequest)) (*Response, error) { - var r = ExistsSourceRequest{Index: index, DocumentID: id} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ExistsSource returns information about whether a document source exists in an index. -// -// -type ExistsSource func(index string, id string, o ...func(*ExistsSourceRequest)) (*Response, error) - -// ExistsSourceRequest configures the Exists Source API request. -// -type ExistsSourceRequest struct { - Index string - DocumentID string - - Preference string - Realtime *bool - Refresh *bool - Routing string - Source interface{} - SourceExcludes []string - SourceIncludes []string - Version *int - VersionType string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ExistsSourceRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "HEAD" - - path.Grow(1 + len(r.Index) + 1 + len(r.DocumentID) + 1 + len("_source")) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_source") - path.WriteString("/") - path.WriteString(r.DocumentID) - - params = make(map[string]string) - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Realtime != nil { - params["realtime"] = strconv.FormatBool(*r.Realtime) - } - - if r.Refresh != nil { - params["refresh"] = strconv.FormatBool(*r.Refresh) - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if source, ok := r.Source.(bool); ok { - params["_source"] = strconv.FormatBool(source) - } else if source, ok := r.Source.(string); ok && source != "" { - params["_source"] = source - } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { - params["_source"] = strings.Join(sources, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if r.Version != nil { - params["version"] = strconv.FormatInt(int64(*r.Version), 10) - } - - if r.VersionType != "" { - params["version_type"] = r.VersionType - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ExistsSource) WithContext(v context.Context) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.ctx = v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f ExistsSource) WithPreference(v string) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.Preference = v - } -} - -// WithRealtime - specify whether to perform the operation in realtime or search mode. -// -func (f ExistsSource) WithRealtime(v bool) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.Realtime = &v - } -} - -// WithRefresh - refresh the shard containing the document before performing the operation. -// -func (f ExistsSource) WithRefresh(v bool) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.Refresh = &v - } -} - -// WithRouting - specific routing value. -// -func (f ExistsSource) WithRouting(v string) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.Routing = v - } -} - -// WithSource - true or false to return the _source field or not, or a list of fields to return. -// -func (f ExistsSource) WithSource(v interface{}) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.Source = v - } -} - -// WithSourceExcludes - a list of fields to exclude from the returned _source field. -// -func (f ExistsSource) WithSourceExcludes(v ...string) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - a list of fields to extract and return from the _source field. -// -func (f ExistsSource) WithSourceIncludes(v ...string) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.SourceIncludes = v - } -} - -// WithVersion - explicit version number for concurrency control. -// -func (f ExistsSource) WithVersion(v int) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.Version = &v - } -} - -// WithVersionType - specific version type. -// -func (f ExistsSource) WithVersionType(v string) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.VersionType = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ExistsSource) WithPretty() func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ExistsSource) WithHuman() func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ExistsSource) WithErrorTrace() func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ExistsSource) WithFilterPath(v ...string) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ExistsSource) WithHeader(h map[string]string) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ExistsSource) WithOpaqueID(s string) func(*ExistsSourceRequest) { - return func(r *ExistsSourceRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.explain.go b/opensearchapi/api.explain.go deleted file mode 100644 index 264262868..000000000 --- a/opensearchapi/api.explain.go +++ /dev/null @@ -1,387 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newExplainFunc(t Transport) Explain { - return func(index string, id string, o ...func(*ExplainRequest)) (*Response, error) { - var r = ExplainRequest{Index: index, DocumentID: id} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Explain returns information about why a specific matches (or doesn't match) a query. -// -// -type Explain func(index string, id string, o ...func(*ExplainRequest)) (*Response, error) - -// ExplainRequest configures the Explain API request. -// -type ExplainRequest struct { - Index string - DocumentID string - - Body io.Reader - - Analyzer string - AnalyzeWildcard *bool - DefaultOperator string - Df string - Lenient *bool - Preference string - Query string - Routing string - Source interface{} - SourceExcludes []string - SourceIncludes []string - StoredFields []string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ExplainRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(r.Index) + 1 + len(r.DocumentID) + 1 + len("_explain")) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_explain") - path.WriteString("/") - path.WriteString(r.DocumentID) - - params = make(map[string]string) - - if r.Analyzer != "" { - params["analyzer"] = r.Analyzer - } - - if r.AnalyzeWildcard != nil { - params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) - } - - if r.DefaultOperator != "" { - params["default_operator"] = r.DefaultOperator - } - - if r.Df != "" { - params["df"] = r.Df - } - - if r.Lenient != nil { - params["lenient"] = strconv.FormatBool(*r.Lenient) - } - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Query != "" { - params["q"] = r.Query - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if source, ok := r.Source.(bool); ok { - params["_source"] = strconv.FormatBool(source) - } else if source, ok := r.Source.(string); ok && source != "" { - params["_source"] = source - } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { - params["_source"] = strings.Join(sources, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if len(r.StoredFields) > 0 { - params["stored_fields"] = strings.Join(r.StoredFields, ",") - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Explain) WithContext(v context.Context) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.ctx = v - } -} - -// WithBody - The query definition using the Query DSL. -// -func (f Explain) WithBody(v io.Reader) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.Body = v - } -} - -// WithAnalyzer - the analyzer for the query string query. -// -func (f Explain) WithAnalyzer(v string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.Analyzer = v - } -} - -// WithAnalyzeWildcard - specify whether wildcards and prefix queries in the query string query should be analyzed (default: false). -// -func (f Explain) WithAnalyzeWildcard(v bool) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.AnalyzeWildcard = &v - } -} - -// WithDefaultOperator - the default operator for query string query (and or or). -// -func (f Explain) WithDefaultOperator(v string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.DefaultOperator = v - } -} - -// WithDf - the default field for query string query (default: _all). -// -func (f Explain) WithDf(v string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.Df = v - } -} - -// WithLenient - specify whether format-based query failures (such as providing text to a numeric field) should be ignored. -// -func (f Explain) WithLenient(v bool) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.Lenient = &v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f Explain) WithPreference(v string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.Preference = v - } -} - -// WithQuery - query in the lucene query string syntax. -// -func (f Explain) WithQuery(v string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.Query = v - } -} - -// WithRouting - specific routing value. -// -func (f Explain) WithRouting(v string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.Routing = v - } -} - -// WithSource - true or false to return the _source field or not, or a list of fields to return. -// -func (f Explain) WithSource(v interface{}) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.Source = v - } -} - -// WithSourceExcludes - a list of fields to exclude from the returned _source field. -// -func (f Explain) WithSourceExcludes(v ...string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - a list of fields to extract and return from the _source field. -// -func (f Explain) WithSourceIncludes(v ...string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.SourceIncludes = v - } -} - -// WithStoredFields - a list of stored fields to return in the response. -// -func (f Explain) WithStoredFields(v ...string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.StoredFields = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Explain) WithPretty() func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Explain) WithHuman() func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Explain) WithErrorTrace() func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Explain) WithFilterPath(v ...string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Explain) WithHeader(h map[string]string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Explain) WithOpaqueID(s string) func(*ExplainRequest) { - return func(r *ExplainRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.field_caps.go b/opensearchapi/api.field_caps.go deleted file mode 100644 index 2ab0d86ea..000000000 --- a/opensearchapi/api.field_caps.go +++ /dev/null @@ -1,299 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newFieldCapsFunc(t Transport) FieldCaps { - return func(o ...func(*FieldCapsRequest)) (*Response, error) { - var r = FieldCapsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// FieldCaps returns the information about the capabilities of fields among multiple indices. -// -// -type FieldCaps func(o ...func(*FieldCapsRequest)) (*Response, error) - -// FieldCapsRequest configures the Field Caps API request. -// -type FieldCapsRequest struct { - Index []string - - Body io.Reader - - AllowNoIndices *bool - ExpandWildcards string - Fields []string - IgnoreUnavailable *bool - IncludeUnmapped *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r FieldCapsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_field_caps")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_field_caps") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if len(r.Fields) > 0 { - params["fields"] = strings.Join(r.Fields, ",") - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.IncludeUnmapped != nil { - params["include_unmapped"] = strconv.FormatBool(*r.IncludeUnmapped) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f FieldCaps) WithContext(v context.Context) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.ctx = v - } -} - -// WithBody - An index filter specified with the Query DSL. -// -func (f FieldCaps) WithBody(v io.Reader) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.Body = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f FieldCaps) WithIndex(v ...string) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f FieldCaps) WithAllowNoIndices(v bool) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f FieldCaps) WithExpandWildcards(v string) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.ExpandWildcards = v - } -} - -// WithFields - a list of field names. -// -func (f FieldCaps) WithFields(v ...string) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.Fields = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f FieldCaps) WithIgnoreUnavailable(v bool) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithIncludeUnmapped - indicates whether unmapped fields should be included in the response.. -// -func (f FieldCaps) WithIncludeUnmapped(v bool) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.IncludeUnmapped = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f FieldCaps) WithPretty() func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f FieldCaps) WithHuman() func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f FieldCaps) WithErrorTrace() func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f FieldCaps) WithFilterPath(v ...string) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f FieldCaps) WithHeader(h map[string]string) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f FieldCaps) WithOpaqueID(s string) func(*FieldCapsRequest) { - return func(r *FieldCapsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.get.go b/opensearchapi/api.get.go deleted file mode 100644 index bff13b716..000000000 --- a/opensearchapi/api.get.go +++ /dev/null @@ -1,345 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newGetFunc(t Transport) Get { - return func(index string, id string, o ...func(*GetRequest)) (*Response, error) { - var r = GetRequest{Index: index, DocumentID: id} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Get returns a document. -// -// -type Get func(index string, id string, o ...func(*GetRequest)) (*Response, error) - -// GetRequest configures the Get API request. -// -type GetRequest struct { - Index string - DocumentID string - - Preference string - Realtime *bool - Refresh *bool - Routing string - Source interface{} - SourceExcludes []string - SourceIncludes []string - StoredFields []string - Version *int - VersionType string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r GetRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(r.Index) + 1 + len("_doc") + 1 + len(r.DocumentID)) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/_doc") - path.WriteString("/") - path.WriteString(r.DocumentID) - - params = make(map[string]string) - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Realtime != nil { - params["realtime"] = strconv.FormatBool(*r.Realtime) - } - - if r.Refresh != nil { - params["refresh"] = strconv.FormatBool(*r.Refresh) - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if source, ok := r.Source.(bool); ok { - params["_source"] = strconv.FormatBool(source) - } else if source, ok := r.Source.(string); ok && source != "" { - params["_source"] = source - } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { - params["_source"] = strings.Join(sources, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if len(r.StoredFields) > 0 { - params["stored_fields"] = strings.Join(r.StoredFields, ",") - } - - if r.Version != nil { - params["version"] = strconv.FormatInt(int64(*r.Version), 10) - } - - if r.VersionType != "" { - params["version_type"] = r.VersionType - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Get) WithContext(v context.Context) func(*GetRequest) { - return func(r *GetRequest) { - r.ctx = v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f Get) WithPreference(v string) func(*GetRequest) { - return func(r *GetRequest) { - r.Preference = v - } -} - -// WithRealtime - specify whether to perform the operation in realtime or search mode. -// -func (f Get) WithRealtime(v bool) func(*GetRequest) { - return func(r *GetRequest) { - r.Realtime = &v - } -} - -// WithRefresh - refresh the shard containing the document before performing the operation. -// -func (f Get) WithRefresh(v bool) func(*GetRequest) { - return func(r *GetRequest) { - r.Refresh = &v - } -} - -// WithRouting - specific routing value. -// -func (f Get) WithRouting(v string) func(*GetRequest) { - return func(r *GetRequest) { - r.Routing = v - } -} - -// WithSource - true or false to return the _source field or not, or a list of fields to return. -// -func (f Get) WithSource(v interface{}) func(*GetRequest) { - return func(r *GetRequest) { - r.Source = v - } -} - -// WithSourceExcludes - a list of fields to exclude from the returned _source field. -// -func (f Get) WithSourceExcludes(v ...string) func(*GetRequest) { - return func(r *GetRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - a list of fields to extract and return from the _source field. -// -func (f Get) WithSourceIncludes(v ...string) func(*GetRequest) { - return func(r *GetRequest) { - r.SourceIncludes = v - } -} - -// WithStoredFields - a list of stored fields to return in the response. -// -func (f Get) WithStoredFields(v ...string) func(*GetRequest) { - return func(r *GetRequest) { - r.StoredFields = v - } -} - -// WithVersion - explicit version number for concurrency control. -// -func (f Get) WithVersion(v int) func(*GetRequest) { - return func(r *GetRequest) { - r.Version = &v - } -} - -// WithVersionType - specific version type. -// -func (f Get) WithVersionType(v string) func(*GetRequest) { - return func(r *GetRequest) { - r.VersionType = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Get) WithPretty() func(*GetRequest) { - return func(r *GetRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Get) WithHuman() func(*GetRequest) { - return func(r *GetRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Get) WithErrorTrace() func(*GetRequest) { - return func(r *GetRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Get) WithFilterPath(v ...string) func(*GetRequest) { - return func(r *GetRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Get) WithHeader(h map[string]string) func(*GetRequest) { - return func(r *GetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Get) WithOpaqueID(s string) func(*GetRequest) { - return func(r *GetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.get_script.go b/opensearchapi/api.get_script.go deleted file mode 100644 index 759a90cb5..000000000 --- a/opensearchapi/api.get_script.go +++ /dev/null @@ -1,237 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newGetScriptFunc(t Transport) GetScript { - return func(id string, o ...func(*GetScriptRequest)) (*Response, error) { - var r = GetScriptRequest{ScriptID: id} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// GetScript returns a script. -// -// -type GetScript func(id string, o ...func(*GetScriptRequest)) (*Response, error) - -// GetScriptRequest configures the Get Script API request. -// -type GetScriptRequest struct { - ScriptID string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r GetScriptRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_scripts") + 1 + len(r.ScriptID)) - path.WriteString("/") - path.WriteString("_scripts") - path.WriteString("/") - path.WriteString(r.ScriptID) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f GetScript) WithContext(v context.Context) func(*GetScriptRequest) { - return func(r *GetScriptRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f GetScript) WithMasterTimeout(v time.Duration) func(*GetScriptRequest) { - return func(r *GetScriptRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f GetScript) WithClusterManagerTimeout(v time.Duration) func(*GetScriptRequest) { - return func(r *GetScriptRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f GetScript) WithPretty() func(*GetScriptRequest) { - return func(r *GetScriptRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f GetScript) WithHuman() func(*GetScriptRequest) { - return func(r *GetScriptRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f GetScript) WithErrorTrace() func(*GetScriptRequest) { - return func(r *GetScriptRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f GetScript) WithFilterPath(v ...string) func(*GetScriptRequest) { - return func(r *GetScriptRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f GetScript) WithHeader(h map[string]string) func(*GetScriptRequest) { - return func(r *GetScriptRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f GetScript) WithOpaqueID(s string) func(*GetScriptRequest) { - return func(r *GetScriptRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.get_script_context.go b/opensearchapi/api.get_script_context.go deleted file mode 100644 index 6b04e1876..000000000 --- a/opensearchapi/api.get_script_context.go +++ /dev/null @@ -1,204 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" -) - -func newGetScriptContextFunc(t Transport) GetScriptContext { - return func(o ...func(*GetScriptContextRequest)) (*Response, error) { - var r = GetScriptContextRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// GetScriptContext returns all script contexts. -// -// This API is experimental. -// -// -type GetScriptContext func(o ...func(*GetScriptContextRequest)) (*Response, error) - -// GetScriptContextRequest configures the Get Script Context API request. -// -type GetScriptContextRequest struct { - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r GetScriptContextRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_script_context")) - path.WriteString("/_script_context") - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f GetScriptContext) WithContext(v context.Context) func(*GetScriptContextRequest) { - return func(r *GetScriptContextRequest) { - r.ctx = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f GetScriptContext) WithPretty() func(*GetScriptContextRequest) { - return func(r *GetScriptContextRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f GetScriptContext) WithHuman() func(*GetScriptContextRequest) { - return func(r *GetScriptContextRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f GetScriptContext) WithErrorTrace() func(*GetScriptContextRequest) { - return func(r *GetScriptContextRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f GetScriptContext) WithFilterPath(v ...string) func(*GetScriptContextRequest) { - return func(r *GetScriptContextRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f GetScriptContext) WithHeader(h map[string]string) func(*GetScriptContextRequest) { - return func(r *GetScriptContextRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f GetScriptContext) WithOpaqueID(s string) func(*GetScriptContextRequest) { - return func(r *GetScriptContextRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.get_script_languages.go b/opensearchapi/api.get_script_languages.go deleted file mode 100644 index 919beaf9f..000000000 --- a/opensearchapi/api.get_script_languages.go +++ /dev/null @@ -1,204 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" -) - -func newGetScriptLanguagesFunc(t Transport) GetScriptLanguages { - return func(o ...func(*GetScriptLanguagesRequest)) (*Response, error) { - var r = GetScriptLanguagesRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// GetScriptLanguages returns available script types, languages and contexts -// -// This API is experimental. -// -// -type GetScriptLanguages func(o ...func(*GetScriptLanguagesRequest)) (*Response, error) - -// GetScriptLanguagesRequest configures the Get Script Languages API request. -// -type GetScriptLanguagesRequest struct { - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r GetScriptLanguagesRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_script_language")) - path.WriteString("/_script_language") - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f GetScriptLanguages) WithContext(v context.Context) func(*GetScriptLanguagesRequest) { - return func(r *GetScriptLanguagesRequest) { - r.ctx = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f GetScriptLanguages) WithPretty() func(*GetScriptLanguagesRequest) { - return func(r *GetScriptLanguagesRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f GetScriptLanguages) WithHuman() func(*GetScriptLanguagesRequest) { - return func(r *GetScriptLanguagesRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f GetScriptLanguages) WithErrorTrace() func(*GetScriptLanguagesRequest) { - return func(r *GetScriptLanguagesRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f GetScriptLanguages) WithFilterPath(v ...string) func(*GetScriptLanguagesRequest) { - return func(r *GetScriptLanguagesRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f GetScriptLanguages) WithHeader(h map[string]string) func(*GetScriptLanguagesRequest) { - return func(r *GetScriptLanguagesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f GetScriptLanguages) WithOpaqueID(s string) func(*GetScriptLanguagesRequest) { - return func(r *GetScriptLanguagesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.get_source.go b/opensearchapi/api.get_source.go deleted file mode 100644 index 05bf6fd6d..000000000 --- a/opensearchapi/api.get_source.go +++ /dev/null @@ -1,330 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newGetSourceFunc(t Transport) GetSource { - return func(index string, id string, o ...func(*GetSourceRequest)) (*Response, error) { - var r = GetSourceRequest{Index: index, DocumentID: id} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// GetSource returns the source of a document. -// -// -type GetSource func(index string, id string, o ...func(*GetSourceRequest)) (*Response, error) - -// GetSourceRequest configures the Get Source API request. -// -type GetSourceRequest struct { - Index string - DocumentID string - - Preference string - Realtime *bool - Refresh *bool - Routing string - // Deprecated: This parameter is similar to SourceIncludes, please use that instead. - Source []string - SourceExcludes []string - SourceIncludes []string - Version *int - VersionType string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r GetSourceRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(r.Index) + 1 + len(r.DocumentID) + 1 + len("_source")) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_source") - path.WriteString("/") - path.WriteString(r.DocumentID) - - params = make(map[string]string) - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Realtime != nil { - params["realtime"] = strconv.FormatBool(*r.Realtime) - } - - if r.Refresh != nil { - params["refresh"] = strconv.FormatBool(*r.Refresh) - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if len(r.Source) > 0 { - params["_source"] = strings.Join(r.Source, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if r.Version != nil { - params["version"] = strconv.FormatInt(int64(*r.Version), 10) - } - - if r.VersionType != "" { - params["version_type"] = r.VersionType - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f GetSource) WithContext(v context.Context) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.ctx = v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f GetSource) WithPreference(v string) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.Preference = v - } -} - -// WithRealtime - specify whether to perform the operation in realtime or search mode. -// -func (f GetSource) WithRealtime(v bool) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.Realtime = &v - } -} - -// WithRefresh - refresh the shard containing the document before performing the operation. -// -func (f GetSource) WithRefresh(v bool) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.Refresh = &v - } -} - -// WithRouting - specific routing value. -// -func (f GetSource) WithRouting(v string) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.Routing = v - } -} - -// WithSource - a list of fields to return. This field is deprecated, please use SourceIncludes instead. -// -func (f GetSource) WithSource(v ...string) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.Source = v - } -} - -// WithSourceExcludes - a list of fields to exclude from the returned _source field. -// -func (f GetSource) WithSourceExcludes(v ...string) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - a list of fields to extract and return from the _source field. -// -func (f GetSource) WithSourceIncludes(v ...string) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.SourceIncludes = v - } -} - -// WithVersion - explicit version number for concurrency control. -// -func (f GetSource) WithVersion(v int) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.Version = &v - } -} - -// WithVersionType - specific version type. -// -func (f GetSource) WithVersionType(v string) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.VersionType = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f GetSource) WithPretty() func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f GetSource) WithHuman() func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f GetSource) WithErrorTrace() func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f GetSource) WithFilterPath(v ...string) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f GetSource) WithHeader(h map[string]string) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f GetSource) WithOpaqueID(s string) func(*GetSourceRequest) { - return func(r *GetSourceRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.index.go b/opensearchapi/api.index.go deleted file mode 100644 index b4044ee4e..000000000 --- a/opensearchapi/api.index.go +++ /dev/null @@ -1,376 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndexFunc(t Transport) Index { - return func(index string, body io.Reader, o ...func(*IndexRequest)) (*Response, error) { - var r = IndexRequest{Index: index, Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Index creates or updates a document in an index. -// -// -type Index func(index string, body io.Reader, o ...func(*IndexRequest)) (*Response, error) - -// IndexRequest configures the Index API request. -// -type IndexRequest struct { - Index string - DocumentID string - - Body io.Reader - - IfPrimaryTerm *int - IfSeqNo *int - OpType string - Pipeline string - Refresh string - RequireAlias *bool - Routing string - Timeout time.Duration - Version *int - VersionType string - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndexRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - if r.DocumentID != "" { - method = "PUT" - } else { - method = "POST" - } - - path.Grow(1 + len(r.Index) + 1 + len("_doc") + 1 + len(r.DocumentID)) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/_doc") - if r.DocumentID != "" { - path.WriteString("/") - path.WriteString(r.DocumentID) - } - - params = make(map[string]string) - - if r.IfPrimaryTerm != nil { - params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10) - } - - if r.IfSeqNo != nil { - params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10) - } - - if r.OpType != "" { - params["op_type"] = r.OpType - } - - if r.Pipeline != "" { - params["pipeline"] = r.Pipeline - } - - if r.Refresh != "" { - params["refresh"] = r.Refresh - } - - if r.RequireAlias != nil { - params["require_alias"] = strconv.FormatBool(*r.RequireAlias) - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Version != nil { - params["version"] = strconv.FormatInt(int64(*r.Version), 10) - } - - if r.VersionType != "" { - params["version_type"] = r.VersionType - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Index) WithContext(v context.Context) func(*IndexRequest) { - return func(r *IndexRequest) { - r.ctx = v - } -} - -// WithDocumentID - document ID. -// -func (f Index) WithDocumentID(v string) func(*IndexRequest) { - return func(r *IndexRequest) { - r.DocumentID = v - } -} - -// WithIfPrimaryTerm - only perform the index operation if the last operation that has changed the document has the specified primary term. -// -func (f Index) WithIfPrimaryTerm(v int) func(*IndexRequest) { - return func(r *IndexRequest) { - r.IfPrimaryTerm = &v - } -} - -// WithIfSeqNo - only perform the index operation if the last operation that has changed the document has the specified sequence number. -// -func (f Index) WithIfSeqNo(v int) func(*IndexRequest) { - return func(r *IndexRequest) { - r.IfSeqNo = &v - } -} - -// WithOpType - explicit operation type. defaults to `index` for requests with an explicit document ID, and to `create`for requests without an explicit document ID. -// -func (f Index) WithOpType(v string) func(*IndexRequest) { - return func(r *IndexRequest) { - r.OpType = v - } -} - -// WithPipeline - the pipeline ID to preprocess incoming documents with. -// -func (f Index) WithPipeline(v string) func(*IndexRequest) { - return func(r *IndexRequest) { - r.Pipeline = v - } -} - -// WithRefresh - if `true` then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes.. -// -func (f Index) WithRefresh(v string) func(*IndexRequest) { - return func(r *IndexRequest) { - r.Refresh = v - } -} - -// WithRequireAlias - when true, requires destination to be an alias. default is false. -// -func (f Index) WithRequireAlias(v bool) func(*IndexRequest) { - return func(r *IndexRequest) { - r.RequireAlias = &v - } -} - -// WithRouting - specific routing value. -// -func (f Index) WithRouting(v string) func(*IndexRequest) { - return func(r *IndexRequest) { - r.Routing = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f Index) WithTimeout(v time.Duration) func(*IndexRequest) { - return func(r *IndexRequest) { - r.Timeout = v - } -} - -// WithVersion - explicit version number for concurrency control. -// -func (f Index) WithVersion(v int) func(*IndexRequest) { - return func(r *IndexRequest) { - r.Version = &v - } -} - -// WithVersionType - specific version type. -// -func (f Index) WithVersionType(v string) func(*IndexRequest) { - return func(r *IndexRequest) { - r.VersionType = v - } -} - -// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the index operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1). -// -func (f Index) WithWaitForActiveShards(v string) func(*IndexRequest) { - return func(r *IndexRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Index) WithPretty() func(*IndexRequest) { - return func(r *IndexRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Index) WithHuman() func(*IndexRequest) { - return func(r *IndexRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Index) WithErrorTrace() func(*IndexRequest) { - return func(r *IndexRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Index) WithFilterPath(v ...string) func(*IndexRequest) { - return func(r *IndexRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Index) WithHeader(h map[string]string) func(*IndexRequest) { - return func(r *IndexRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Index) WithOpaqueID(s string) func(*IndexRequest) { - return func(r *IndexRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.add_block.go b/opensearchapi/api.indices.add_block.go deleted file mode 100644 index 5a8705b25..000000000 --- a/opensearchapi/api.indices.add_block.go +++ /dev/null @@ -1,294 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesAddBlockFunc(t Transport) IndicesAddBlock { - return func(index []string, block string, o ...func(*IndicesAddBlockRequest)) (*Response, error) { - var r = IndicesAddBlockRequest{Index: index, Block: block} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesAddBlock adds a block to an index. -// -// -type IndicesAddBlock func(index []string, block string, o ...func(*IndicesAddBlockRequest)) (*Response, error) - -// IndicesAddBlockRequest configures the Indices Add Block API request. -// -type IndicesAddBlockRequest struct { - Index []string - - Block string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesAddBlockRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_block") + 1 + len(r.Block)) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - path.WriteString("/") - path.WriteString("_block") - path.WriteString("/") - path.WriteString(r.Block) - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesAddBlock) WithContext(v context.Context) func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.ctx = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesAddBlock) WithAllowNoIndices(v bool) func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesAddBlock) WithExpandWildcards(v string) func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesAddBlock) WithIgnoreUnavailable(v bool) func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesAddBlock) WithMasterTimeout(v time.Duration) func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesAddBlock) WithClusterManagerTimeout(v time.Duration) func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesAddBlock) WithTimeout(v time.Duration) func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesAddBlock) WithPretty() func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesAddBlock) WithHuman() func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesAddBlock) WithErrorTrace() func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesAddBlock) WithFilterPath(v ...string) func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesAddBlock) WithHeader(h map[string]string) func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesAddBlock) WithOpaqueID(s string) func(*IndicesAddBlockRequest) { - return func(r *IndicesAddBlockRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.analyze.go b/opensearchapi/api.indices.analyze.go deleted file mode 100644 index cd8029d35..000000000 --- a/opensearchapi/api.indices.analyze.go +++ /dev/null @@ -1,236 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" -) - -func newIndicesAnalyzeFunc(t Transport) IndicesAnalyze { - return func(o ...func(*IndicesAnalyzeRequest)) (*Response, error) { - var r = IndicesAnalyzeRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesAnalyze performs the analysis process on a text and return the tokens breakdown of the text. -// -// -type IndicesAnalyze func(o ...func(*IndicesAnalyzeRequest)) (*Response, error) - -// IndicesAnalyzeRequest configures the Indices Analyze API request. -// -type IndicesAnalyzeRequest struct { - Index string - - Body io.Reader - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesAnalyzeRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(r.Index) + 1 + len("_analyze")) - if r.Index != "" { - path.WriteString("/") - path.WriteString(r.Index) - } - path.WriteString("/") - path.WriteString("_analyze") - - params = make(map[string]string) - - if r.Index != "" { - params["index"] = r.Index - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesAnalyze) WithContext(v context.Context) func(*IndicesAnalyzeRequest) { - return func(r *IndicesAnalyzeRequest) { - r.ctx = v - } -} - -// WithBody - Define analyzer/tokenizer parameters and the text on which the analysis should be performed. -// -func (f IndicesAnalyze) WithBody(v io.Reader) func(*IndicesAnalyzeRequest) { - return func(r *IndicesAnalyzeRequest) { - r.Body = v - } -} - -// WithIndex - the name of the index to scope the operation. -// -func (f IndicesAnalyze) WithIndex(v string) func(*IndicesAnalyzeRequest) { - return func(r *IndicesAnalyzeRequest) { - r.Index = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesAnalyze) WithPretty() func(*IndicesAnalyzeRequest) { - return func(r *IndicesAnalyzeRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesAnalyze) WithHuman() func(*IndicesAnalyzeRequest) { - return func(r *IndicesAnalyzeRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesAnalyze) WithErrorTrace() func(*IndicesAnalyzeRequest) { - return func(r *IndicesAnalyzeRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesAnalyze) WithFilterPath(v ...string) func(*IndicesAnalyzeRequest) { - return func(r *IndicesAnalyzeRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesAnalyze) WithHeader(h map[string]string) func(*IndicesAnalyzeRequest) { - return func(r *IndicesAnalyzeRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesAnalyze) WithOpaqueID(s string) func(*IndicesAnalyzeRequest) { - return func(r *IndicesAnalyzeRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.clear_cache.go b/opensearchapi/api.indices.clear_cache.go deleted file mode 100644 index dd62c87ce..000000000 --- a/opensearchapi/api.indices.clear_cache.go +++ /dev/null @@ -1,316 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesClearCacheFunc(t Transport) IndicesClearCache { - return func(o ...func(*IndicesClearCacheRequest)) (*Response, error) { - var r = IndicesClearCacheRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesClearCache clears all or specific caches for one or more indices. -// -// -type IndicesClearCache func(o ...func(*IndicesClearCacheRequest)) (*Response, error) - -// IndicesClearCacheRequest configures the Indices Clear Cache API request. -// -type IndicesClearCacheRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - Fielddata *bool - Fields []string - IgnoreUnavailable *bool - Query *bool - Request *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesClearCacheRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_cache") + 1 + len("clear")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_cache") - path.WriteString("/") - path.WriteString("clear") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Fielddata != nil { - params["fielddata"] = strconv.FormatBool(*r.Fielddata) - } - - if len(r.Fields) > 0 { - params["fields"] = strings.Join(r.Fields, ",") - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if len(r.Index) > 0 { - params["index"] = strings.Join(r.Index, ",") - } - - if r.Query != nil { - params["query"] = strconv.FormatBool(*r.Query) - } - - if r.Request != nil { - params["request"] = strconv.FormatBool(*r.Request) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesClearCache) WithContext(v context.Context) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index name to limit the operation. -// -func (f IndicesClearCache) WithIndex(v ...string) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesClearCache) WithAllowNoIndices(v bool) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesClearCache) WithExpandWildcards(v string) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.ExpandWildcards = v - } -} - -// WithFielddata - clear field data. -// -func (f IndicesClearCache) WithFielddata(v bool) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.Fielddata = &v - } -} - -// WithFields - a list of fields to clear when using the `fielddata` parameter (default: all). -// -func (f IndicesClearCache) WithFields(v ...string) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.Fields = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesClearCache) WithIgnoreUnavailable(v bool) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithQuery - clear query caches. -// -func (f IndicesClearCache) WithQuery(v bool) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.Query = &v - } -} - -// WithRequest - clear request cache. -// -func (f IndicesClearCache) WithRequest(v bool) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.Request = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesClearCache) WithPretty() func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesClearCache) WithHuman() func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesClearCache) WithErrorTrace() func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesClearCache) WithFilterPath(v ...string) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesClearCache) WithHeader(h map[string]string) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesClearCache) WithOpaqueID(s string) func(*IndicesClearCacheRequest) { - return func(r *IndicesClearCacheRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.clone.go b/opensearchapi/api.indices.clone.go deleted file mode 100644 index 2c1bce0e3..000000000 --- a/opensearchapi/api.indices.clone.go +++ /dev/null @@ -1,282 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" - "time" -) - -func newIndicesCloneFunc(t Transport) IndicesClone { - return func(index string, target string, o ...func(*IndicesCloneRequest)) (*Response, error) { - var r = IndicesCloneRequest{Index: index, Target: target} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesClone clones an index -// -// -type IndicesClone func(index string, target string, o ...func(*IndicesCloneRequest)) (*Response, error) - -// IndicesCloneRequest configures the Indices Clone API request. -// -type IndicesCloneRequest struct { - Index string - - Body io.Reader - - Target string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesCloneRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len(r.Index) + 1 + len("_clone") + 1 + len(r.Target)) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_clone") - path.WriteString("/") - path.WriteString(r.Target) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesClone) WithContext(v context.Context) func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - r.ctx = v - } -} - -// WithBody - The configuration for the target index (`settings` and `aliases`). -// -func (f IndicesClone) WithBody(v io.Reader) func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - r.Body = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesClone) WithMasterTimeout(v time.Duration) func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesClone) WithClusterManagerTimeout(v time.Duration) func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesClone) WithTimeout(v time.Duration) func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - set the number of active shards to wait for on the cloned index before the operation returns.. -// -func (f IndicesClone) WithWaitForActiveShards(v string) func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesClone) WithPretty() func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesClone) WithHuman() func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesClone) WithErrorTrace() func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesClone) WithFilterPath(v ...string) func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesClone) WithHeader(h map[string]string) func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesClone) WithOpaqueID(s string) func(*IndicesCloneRequest) { - return func(r *IndicesCloneRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.close.go b/opensearchapi/api.indices.close.go deleted file mode 100644 index 9ed4e2af7..000000000 --- a/opensearchapi/api.indices.close.go +++ /dev/null @@ -1,303 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesCloseFunc(t Transport) IndicesClose { - return func(index []string, o ...func(*IndicesCloseRequest)) (*Response, error) { - var r = IndicesCloseRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesClose closes an index. -// -// -type IndicesClose func(index []string, o ...func(*IndicesCloseRequest)) (*Response, error) - -// IndicesCloseRequest configures the Indices Close API request. -// -type IndicesCloseRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesCloseRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_close")) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - path.WriteString("/") - path.WriteString("_close") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesClose) WithContext(v context.Context) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.ctx = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesClose) WithAllowNoIndices(v bool) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesClose) WithExpandWildcards(v string) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesClose) WithIgnoreUnavailable(v bool) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesClose) WithMasterTimeout(v time.Duration) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesClose) WithClusterManagerTimeout(v time.Duration) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesClose) WithTimeout(v time.Duration) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - sets the number of active shards to wait for before the operation returns. set to `index-setting` to wait according to the index setting `index.write.wait_for_active_shards`, or `all` to wait for all shards, or an integer. defaults to `0`.. -// -func (f IndicesClose) WithWaitForActiveShards(v string) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesClose) WithPretty() func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesClose) WithHuman() func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesClose) WithErrorTrace() func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesClose) WithFilterPath(v ...string) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesClose) WithHeader(h map[string]string) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesClose) WithOpaqueID(s string) func(*IndicesCloseRequest) { - return func(r *IndicesCloseRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.create.go b/opensearchapi/api.indices.create.go deleted file mode 100644 index bee47ff15..000000000 --- a/opensearchapi/api.indices.create.go +++ /dev/null @@ -1,276 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" - "time" -) - -func newIndicesCreateFunc(t Transport) IndicesCreate { - return func(index string, o ...func(*IndicesCreateRequest)) (*Response, error) { - var r = IndicesCreateRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesCreate creates an index with optional settings and mappings. -// -// -type IndicesCreate func(index string, o ...func(*IndicesCreateRequest)) (*Response, error) - -// IndicesCreateRequest configures the Indices Create API request. -// -type IndicesCreateRequest struct { - Index string - - Body io.Reader - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesCreateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len(r.Index)) - path.WriteString("/") - path.WriteString(r.Index) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesCreate) WithContext(v context.Context) func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - r.ctx = v - } -} - -// WithBody - The configuration for the index (`settings` and `mappings`). -// -func (f IndicesCreate) WithBody(v io.Reader) func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - r.Body = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesCreate) WithMasterTimeout(v time.Duration) func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesCreate) WithClusterManagerTimeout(v time.Duration) func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesCreate) WithTimeout(v time.Duration) func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - set the number of active shards to wait for before the operation returns.. -// -func (f IndicesCreate) WithWaitForActiveShards(v string) func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesCreate) WithPretty() func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesCreate) WithHuman() func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesCreate) WithErrorTrace() func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesCreate) WithFilterPath(v ...string) func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesCreate) WithHeader(h map[string]string) func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesCreate) WithOpaqueID(s string) func(*IndicesCreateRequest) { - return func(r *IndicesCreateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.create_datastream.go b/opensearchapi/api.indices.create_datastream.go deleted file mode 100644 index d7094b356..000000000 --- a/opensearchapi/api.indices.create_datastream.go +++ /dev/null @@ -1,177 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" -) - -func newIndicesCreateDataStreamFunc(t Transport) IndicesCreateDataStream { - return func(name string, o ...func(*IndicesCreateDataStreamRequest)) (*Response, error) { - var r = IndicesCreateDataStreamRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesCreateDataStream creates a data stream. -type IndicesCreateDataStream func(index string, o ...func(*IndicesCreateDataStreamRequest)) (*Response, error) - -// IndicesCreateDataStreamRequest configures the Indices Create Data Stream API request. -type IndicesCreateDataStreamRequest struct { - Name string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do execute the request and returns response or error. -func (r IndicesCreateDataStreamRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len("_data_stream") + 1 + len(r.Name)) - path.WriteString("/_data_stream/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, nil -} - -// WithContext sets the request context. -func (f IndicesCreateDataStream) WithContext(v context.Context) func(*IndicesCreateDataStreamRequest) { - return func(r *IndicesCreateDataStreamRequest) { - r.ctx = v - } -} - -// WithPretty makes the response body pretty-printed. -func (f IndicesCreateDataStream) WithPretty() func(*IndicesCreateDataStreamRequest) { - return func(r *IndicesCreateDataStreamRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -func (f IndicesCreateDataStream) WithHuman() func(*IndicesCreateDataStreamRequest) { - return func(r *IndicesCreateDataStreamRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -func (f IndicesCreateDataStream) WithErrorTrace() func(*IndicesCreateDataStreamRequest) { - return func(r *IndicesCreateDataStreamRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -func (f IndicesCreateDataStream) WithFilterPath(v ...string) func(*IndicesCreateDataStreamRequest) { - return func(r *IndicesCreateDataStreamRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -func (f IndicesCreateDataStream) WithHeader(h map[string]string) func(*IndicesCreateDataStreamRequest) { - return func(r *IndicesCreateDataStreamRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -func (f IndicesCreateDataStream) WithOpaqueID(s string) func(*IndicesCreateDataStreamRequest) { - return func(r *IndicesCreateDataStreamRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.datastream_test.go b/opensearchapi/api.indices.datastream_test.go deleted file mode 100644 index a6aeb1274..000000000 --- a/opensearchapi/api.indices.datastream_test.go +++ /dev/null @@ -1,246 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -//go:build integration -// +build integration - -package opensearchapi_test - -import ( - "context" - "fmt" - "io/ioutil" - "net/http" - "strings" - "testing" - "time" - - "github.com/kinbiko/jsonassert" - "github.com/opensearch-project/opensearch-go/v2" - "github.com/opensearch-project/opensearch-go/v2/opensearchapi" - "github.com/stretchr/testify/require" -) - -type DataStreamRequest interface { - Do(context.Context, opensearchapi.Transport) (*opensearchapi.Response, error) -} - -func TestIndicesDataStreams_Do(t *testing.T) { - // We need two datastreams to ensure endpoints that fetch both are tested appropriately - dataStream1 := fmt.Sprintf("demo-1-%s", time.Now().Format("2006-01-02-15-04-05")) - dataStream2 := fmt.Sprintf("demo-2-%s", time.Now().Format("2006-01-02-15-04-05")) - - tests := []struct { - name string - r DataStreamRequest - want *opensearchapi.Response - wantBody string - wantErr bool - }{ - { - name: "TestIndicesCreateDataStreamRequest_Do", - r: opensearchapi.IndicesCreateDataStreamRequest{ - Name: dataStream1, - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: `{"acknowledged":true}`, - wantErr: false, - }, - { - name: "TestIndicesCreateDataStream2Request_Do", - r: opensearchapi.IndicesCreateDataStreamRequest{ - Name: dataStream2, - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: `{"acknowledged":true}`, - wantErr: false, - }, - { - name: "TestIndicesGetDataStreamRequest_Do", - r: opensearchapi.IndicesGetDataStreamRequest{ - Name: dataStream1, - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantErr: false, - }, - { - name: "TestIndicesGetAllDataStreamsRequest_Do", - r: opensearchapi.IndicesGetDataStreamRequest{ - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantErr: false, - }, - { - name: "TestIndicesGetStatsDataStreamRequest_Do", - r: opensearchapi.IndicesGetDataStreamStatsRequest{ - Name: dataStream1, - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: fmt.Sprintf(`{"_shards":{"total":2,"successful":1,"failed":0},"data_stream_count":1,"backing_indices":1,"total_store_size":"208b","total_store_size_bytes":208,"data_streams":[{"data_stream":"%s","backing_indices":1,"store_size":"208b","store_size_bytes":208,"maximum_timestamp":0}]}`, dataStream1), - wantErr: false, - }, - { - name: "TestIndicesGetAllStatsDataStreamRequest_Do", - r: opensearchapi.IndicesGetDataStreamStatsRequest{ - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: fmt.Sprintf(`{"_shards":{"total":4,"successful":2,"failed":0},"data_stream_count":2,"backing_indices":2,"total_store_size":"416b","total_store_size_bytes":416,"data_streams":["<>",{"data_stream":"%s","backing_indices":1,"store_size":"208b","store_size_bytes":208,"maximum_timestamp":0},{"data_stream":"%s","backing_indices":1,"store_size":"208b","store_size_bytes":208,"maximum_timestamp":0}]}`, dataStream2, dataStream1), - wantErr: false, - }, - { - name: "TestIndicesDeleteDataStreamRequest_Do", - r: opensearchapi.IndicesDeleteDataStreamRequest{ - Name: dataStream1, - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: `{"acknowledged":true}`, - wantErr: false, - }, - { - name: "TestIndicesDeleteDataStream2Request_Do", - r: opensearchapi.IndicesDeleteDataStreamRequest{ - Name: dataStream2, - Pretty: true, - Human: true, - ErrorTrace: true, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - }, - }, - want: &opensearchapi.Response{ - StatusCode: 200, - Header: http.Header{ - "Content-Type": []string{"application/json; charset=UTF-8"}, - }, - }, - wantBody: `{"acknowledged":true}`, - wantErr: false, - }, - } - - client, err := opensearch.NewDefaultClient() - require.NoError(t, err) - - iPut := opensearchapi.IndicesPutIndexTemplateRequest{ - Name: fmt.Sprintf("demo-data-template"), - Pretty: true, - Human: true, - ErrorTrace: true, - Body: strings.NewReader(fmt.Sprintf(`{"index_patterns": ["demo-*"], "data_stream": {}, "priority": 100} }`)), - } - - iPutResponse, err := iPut.Do(context.Background(), client) - require.NoError(t, err) - require.Equalf(t, false, iPutResponse.IsError(), - "Error when creating index template: %s", iPutResponse.String()) - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := tt.r.Do(context.Background(), client) - if (err != nil) != tt.wantErr { - t.Errorf("Do() error = %v, wantErr %v", err, tt.wantErr) - return - } - - require.Equalf(t, got.IsError(), tt.wantErr, "Do() got = %v, want %v", got.IsError(), tt.wantErr) - require.Equalf(t, got.StatusCode, tt.want.StatusCode, "Do() got = %v, want %v", got.StatusCode, tt.want.StatusCode) - - if tt.wantBody != "" { - for name, value := range tt.want.Header { - require.Contains(t, got.Header, name) - require.Equal(t, value, got.Header[name]) - } - - defer got.Body.Close() - body, err := ioutil.ReadAll(got.Body) - require.NoError(t, err) - - ja := jsonassert.New(t) - ja.Assertf(string(body), tt.wantBody) - } - }) - } -} diff --git a/opensearchapi/api.indices.delete.go b/opensearchapi/api.indices.delete.go deleted file mode 100644 index 96ffaa6f9..000000000 --- a/opensearchapi/api.indices.delete.go +++ /dev/null @@ -1,288 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesDeleteFunc(t Transport) IndicesDelete { - return func(index []string, o ...func(*IndicesDeleteRequest)) (*Response, error) { - var r = IndicesDeleteRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesDelete deletes an index. -// -// -type IndicesDelete func(index []string, o ...func(*IndicesDeleteRequest)) (*Response, error) - -// IndicesDeleteRequest configures the Indices Delete API request. -// -type IndicesDeleteRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesDeleteRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len(strings.Join(r.Index, ","))) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesDelete) WithContext(v context.Context) func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.ctx = v - } -} - -// WithAllowNoIndices - ignore if a wildcard expression resolves to no concrete indices (default: false). -// -func (f IndicesDelete) WithAllowNoIndices(v bool) func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether wildcard expressions should get expanded to open or closed indices (default: open). -// -func (f IndicesDelete) WithExpandWildcards(v string) func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - ignore unavailable indexes (default: false). -// -func (f IndicesDelete) WithIgnoreUnavailable(v bool) func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesDelete) WithMasterTimeout(v time.Duration) func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesDelete) WithClusterManagerTimeout(v time.Duration) func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesDelete) WithTimeout(v time.Duration) func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesDelete) WithPretty() func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesDelete) WithHuman() func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesDelete) WithErrorTrace() func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesDelete) WithFilterPath(v ...string) func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesDelete) WithHeader(h map[string]string) func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesDelete) WithOpaqueID(s string) func(*IndicesDeleteRequest) { - return func(r *IndicesDeleteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.delete_alias.go b/opensearchapi/api.indices.delete_alias.go deleted file mode 100644 index 069e4e081..000000000 --- a/opensearchapi/api.indices.delete_alias.go +++ /dev/null @@ -1,254 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newIndicesDeleteAliasFunc(t Transport) IndicesDeleteAlias { - return func(index []string, name []string, o ...func(*IndicesDeleteAliasRequest)) (*Response, error) { - var r = IndicesDeleteAliasRequest{Index: index, Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesDeleteAlias deletes an alias. -// -// -type IndicesDeleteAlias func(index []string, name []string, o ...func(*IndicesDeleteAliasRequest)) (*Response, error) - -// IndicesDeleteAliasRequest configures the Indices Delete Alias API request. -// -type IndicesDeleteAliasRequest struct { - Index []string - - Name []string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesDeleteAliasRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_aliases") + 1 + len(strings.Join(r.Name, ","))) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - path.WriteString("/") - path.WriteString("_aliases") - path.WriteString("/") - path.WriteString(strings.Join(r.Name, ",")) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesDeleteAlias) WithContext(v context.Context) func(*IndicesDeleteAliasRequest) { - return func(r *IndicesDeleteAliasRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesDeleteAlias) WithMasterTimeout(v time.Duration) func(*IndicesDeleteAliasRequest) { - return func(r *IndicesDeleteAliasRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesDeleteAlias) WithClusterManagerTimeout(v time.Duration) func(*IndicesDeleteAliasRequest) { - return func(r *IndicesDeleteAliasRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit timestamp for the document. -// -func (f IndicesDeleteAlias) WithTimeout(v time.Duration) func(*IndicesDeleteAliasRequest) { - return func(r *IndicesDeleteAliasRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesDeleteAlias) WithPretty() func(*IndicesDeleteAliasRequest) { - return func(r *IndicesDeleteAliasRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesDeleteAlias) WithHuman() func(*IndicesDeleteAliasRequest) { - return func(r *IndicesDeleteAliasRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesDeleteAlias) WithErrorTrace() func(*IndicesDeleteAliasRequest) { - return func(r *IndicesDeleteAliasRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesDeleteAlias) WithFilterPath(v ...string) func(*IndicesDeleteAliasRequest) { - return func(r *IndicesDeleteAliasRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesDeleteAlias) WithHeader(h map[string]string) func(*IndicesDeleteAliasRequest) { - return func(r *IndicesDeleteAliasRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesDeleteAlias) WithOpaqueID(s string) func(*IndicesDeleteAliasRequest) { - return func(r *IndicesDeleteAliasRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.delete_datastream.go b/opensearchapi/api.indices.delete_datastream.go deleted file mode 100644 index 958d46b3d..000000000 --- a/opensearchapi/api.indices.delete_datastream.go +++ /dev/null @@ -1,203 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newIndicesDeleteDataStreamFunc(t Transport) IndicesDeleteDataStream { - return func(name string, o ...func(*IndicesDeleteDataStreamRequest)) (*Response, error) { - var r = IndicesDeleteDataStreamRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesDeleteDataStream deletes the backing indices of a data stream and then deletes the data stream itself. -type IndicesDeleteDataStream func(name string, o ...func(*IndicesDeleteDataStreamRequest)) (*Response, error) - -// IndicesDeleteDataStreamRequest configures the Data Stream Delete Template API request. -type IndicesDeleteDataStreamRequest struct { - Name string - - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do execute the request and returns response or error. -func (r IndicesDeleteDataStreamRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len("_data_stream") + 1 + len(r.Name)) - path.WriteString("/_data_stream/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, nil -} - -// WithContext sets the request context. -func (f IndicesDeleteDataStream) WithContext(v context.Context) func(*IndicesDeleteDataStreamRequest) { - return func(r *IndicesDeleteDataStreamRequest) { - r.ctx = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -func (f IndicesDeleteDataStream) WithClusterManagerTimeout(v time.Duration) func(*IndicesDeleteDataStreamRequest) { - return func(r *IndicesDeleteDataStreamRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -func (f IndicesDeleteDataStream) WithTimeout(v time.Duration) func(*IndicesDeleteDataStreamRequest) { - return func(r *IndicesDeleteDataStreamRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -func (f IndicesDeleteDataStream) WithPretty() func(*IndicesDeleteDataStreamRequest) { - return func(r *IndicesDeleteDataStreamRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -func (f IndicesDeleteDataStream) WithHuman() func(*IndicesDeleteDataStreamRequest) { - return func(r *IndicesDeleteDataStreamRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -func (f IndicesDeleteDataStream) WithErrorTrace() func(*IndicesDeleteDataStreamRequest) { - return func(r *IndicesDeleteDataStreamRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -func (f IndicesDeleteDataStream) WithFilterPath(v ...string) func(*IndicesDeleteDataStreamRequest) { - return func(r *IndicesDeleteDataStreamRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -func (f IndicesDeleteDataStream) WithHeader(h map[string]string) func(*IndicesDeleteDataStreamRequest) { - return func(r *IndicesDeleteDataStreamRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -func (f IndicesDeleteDataStream) WithOpaqueID(s string) func(*IndicesDeleteDataStreamRequest) { - return func(r *IndicesDeleteDataStreamRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.delete_index_template.go b/opensearchapi/api.indices.delete_index_template.go deleted file mode 100644 index 82a60a087..000000000 --- a/opensearchapi/api.indices.delete_index_template.go +++ /dev/null @@ -1,250 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newIndicesDeleteIndexTemplateFunc(t Transport) IndicesDeleteIndexTemplate { - return func(name string, o ...func(*IndicesDeleteIndexTemplateRequest)) (*Response, error) { - var r = IndicesDeleteIndexTemplateRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesDeleteIndexTemplate deletes an index template. -// -// -type IndicesDeleteIndexTemplate func(name string, o ...func(*IndicesDeleteIndexTemplateRequest)) (*Response, error) - -// IndicesDeleteIndexTemplateRequest configures the Indices Delete Index Template API request. -// -type IndicesDeleteIndexTemplateRequest struct { - Name string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesDeleteIndexTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len("_index_template") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_index_template") - path.WriteString("/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesDeleteIndexTemplate) WithContext(v context.Context) func(*IndicesDeleteIndexTemplateRequest) { - return func(r *IndicesDeleteIndexTemplateRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesDeleteIndexTemplate) WithMasterTimeout(v time.Duration) func(*IndicesDeleteIndexTemplateRequest) { - return func(r *IndicesDeleteIndexTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesDeleteIndexTemplate) WithClusterManagerTimeout(v time.Duration) func(*IndicesDeleteIndexTemplateRequest) { - return func(r *IndicesDeleteIndexTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesDeleteIndexTemplate) WithTimeout(v time.Duration) func(*IndicesDeleteIndexTemplateRequest) { - return func(r *IndicesDeleteIndexTemplateRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesDeleteIndexTemplate) WithPretty() func(*IndicesDeleteIndexTemplateRequest) { - return func(r *IndicesDeleteIndexTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesDeleteIndexTemplate) WithHuman() func(*IndicesDeleteIndexTemplateRequest) { - return func(r *IndicesDeleteIndexTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesDeleteIndexTemplate) WithErrorTrace() func(*IndicesDeleteIndexTemplateRequest) { - return func(r *IndicesDeleteIndexTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesDeleteIndexTemplate) WithFilterPath(v ...string) func(*IndicesDeleteIndexTemplateRequest) { - return func(r *IndicesDeleteIndexTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesDeleteIndexTemplate) WithHeader(h map[string]string) func(*IndicesDeleteIndexTemplateRequest) { - return func(r *IndicesDeleteIndexTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesDeleteIndexTemplate) WithOpaqueID(s string) func(*IndicesDeleteIndexTemplateRequest) { - return func(r *IndicesDeleteIndexTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.delete_template.go b/opensearchapi/api.indices.delete_template.go deleted file mode 100644 index 82e0f98bb..000000000 --- a/opensearchapi/api.indices.delete_template.go +++ /dev/null @@ -1,263 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use newIndicesDeleteIndexTemplateFunc instead -func newIndicesDeleteTemplateFunc(t Transport) IndicesDeleteTemplate { - return func(name string, o ...func(*IndicesDeleteTemplateRequest)) (*Response, error) { - var r = IndicesDeleteTemplateRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesDeleteTemplate deletes an index template. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -type IndicesDeleteTemplate func(name string, o ...func(*IndicesDeleteTemplateRequest)) (*Response, error) - -// IndicesDeleteTemplateRequest configures the Indices Delete Template API request. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplateRequest instead -type IndicesDeleteTemplateRequest struct { - Name string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplateRequest instead -func (r IndicesDeleteTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len("_template") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_template") - path.WriteString("/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -func (f IndicesDeleteTemplate) WithContext(v context.Context) func(*IndicesDeleteTemplateRequest) { - return func(r *IndicesDeleteTemplateRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -func (f IndicesDeleteTemplate) WithMasterTimeout(v time.Duration) func(*IndicesDeleteTemplateRequest) { - return func(r *IndicesDeleteTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -func (f IndicesDeleteTemplate) WithClusterManagerTimeout(v time.Duration) func(*IndicesDeleteTemplateRequest) { - return func(r *IndicesDeleteTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -func (f IndicesDeleteTemplate) WithTimeout(v time.Duration) func(*IndicesDeleteTemplateRequest) { - return func(r *IndicesDeleteTemplateRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -func (f IndicesDeleteTemplate) WithPretty() func(*IndicesDeleteTemplateRequest) { - return func(r *IndicesDeleteTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -func (f IndicesDeleteTemplate) WithHuman() func(*IndicesDeleteTemplateRequest) { - return func(r *IndicesDeleteTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -func (f IndicesDeleteTemplate) WithErrorTrace() func(*IndicesDeleteTemplateRequest) { - return func(r *IndicesDeleteTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -func (f IndicesDeleteTemplate) WithFilterPath(v ...string) func(*IndicesDeleteTemplateRequest) { - return func(r *IndicesDeleteTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -func (f IndicesDeleteTemplate) WithHeader(h map[string]string) func(*IndicesDeleteTemplateRequest) { - return func(r *IndicesDeleteTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesDeleteIndexTemplate instead -func (f IndicesDeleteTemplate) WithOpaqueID(s string) func(*IndicesDeleteTemplateRequest) { - return func(r *IndicesDeleteTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.disk_usage.go b/opensearchapi/api.indices.disk_usage.go deleted file mode 100644 index b3c12c97e..000000000 --- a/opensearchapi/api.indices.disk_usage.go +++ /dev/null @@ -1,276 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesDiskUsageFunc(t Transport) IndicesDiskUsage { - return func(index string, o ...func(*IndicesDiskUsageRequest)) (*Response, error) { - var r = IndicesDiskUsageRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesDiskUsage analyzes the disk usage of each field of an index or data stream -// -// This API is experimental. -// -// -type IndicesDiskUsage func(index string, o ...func(*IndicesDiskUsageRequest)) (*Response, error) - -// IndicesDiskUsageRequest configures the Indices Disk Usage API request. -// -type IndicesDiskUsageRequest struct { - Index string - - AllowNoIndices *bool - ExpandWildcards string - Flush *bool - IgnoreUnavailable *bool - RunExpensiveTasks *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesDiskUsageRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(r.Index) + 1 + len("_disk_usage")) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_disk_usage") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Flush != nil { - params["flush"] = strconv.FormatBool(*r.Flush) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.RunExpensiveTasks != nil { - params["run_expensive_tasks"] = strconv.FormatBool(*r.RunExpensiveTasks) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesDiskUsage) WithContext(v context.Context) func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - r.ctx = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesDiskUsage) WithAllowNoIndices(v bool) func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesDiskUsage) WithExpandWildcards(v string) func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - r.ExpandWildcards = v - } -} - -// WithFlush - whether flush or not before analyzing the index disk usage. defaults to true. -// -func (f IndicesDiskUsage) WithFlush(v bool) func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - r.Flush = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesDiskUsage) WithIgnoreUnavailable(v bool) func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithRunExpensiveTasks - must be set to [true] in order for the task to be performed. defaults to false.. -// -func (f IndicesDiskUsage) WithRunExpensiveTasks(v bool) func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - r.RunExpensiveTasks = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesDiskUsage) WithPretty() func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesDiskUsage) WithHuman() func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesDiskUsage) WithErrorTrace() func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesDiskUsage) WithFilterPath(v ...string) func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesDiskUsage) WithHeader(h map[string]string) func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesDiskUsage) WithOpaqueID(s string) func(*IndicesDiskUsageRequest) { - return func(r *IndicesDiskUsageRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.exists.go b/opensearchapi/api.indices.exists.go deleted file mode 100644 index fc3fd2991..000000000 --- a/opensearchapi/api.indices.exists.go +++ /dev/null @@ -1,285 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesExistsFunc(t Transport) IndicesExists { - return func(index []string, o ...func(*IndicesExistsRequest)) (*Response, error) { - var r = IndicesExistsRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesExists returns information about whether a particular index exists. -// -// -type IndicesExists func(index []string, o ...func(*IndicesExistsRequest)) (*Response, error) - -// IndicesExistsRequest configures the Indices Exists API request. -// -type IndicesExistsRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - FlatSettings *bool - IgnoreUnavailable *bool - IncludeDefaults *bool - Local *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesExistsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "HEAD" - - path.Grow(1 + len(strings.Join(r.Index, ","))) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.IncludeDefaults != nil { - params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesExists) WithContext(v context.Context) func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.ctx = v - } -} - -// WithAllowNoIndices - ignore if a wildcard expression resolves to no concrete indices (default: false). -// -func (f IndicesExists) WithAllowNoIndices(v bool) func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether wildcard expressions should get expanded to open or closed indices (default: open). -// -func (f IndicesExists) WithExpandWildcards(v string) func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.ExpandWildcards = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f IndicesExists) WithFlatSettings(v bool) func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.FlatSettings = &v - } -} - -// WithIgnoreUnavailable - ignore unavailable indexes (default: false). -// -func (f IndicesExists) WithIgnoreUnavailable(v bool) func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithIncludeDefaults - whether to return all default setting for each of the indices.. -// -func (f IndicesExists) WithIncludeDefaults(v bool) func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.IncludeDefaults = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f IndicesExists) WithLocal(v bool) func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.Local = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesExists) WithPretty() func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesExists) WithHuman() func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesExists) WithErrorTrace() func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesExists) WithFilterPath(v ...string) func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesExists) WithHeader(h map[string]string) func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesExists) WithOpaqueID(s string) func(*IndicesExistsRequest) { - return func(r *IndicesExistsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.exists_alias.go b/opensearchapi/api.indices.exists_alias.go deleted file mode 100644 index 63020048e..000000000 --- a/opensearchapi/api.indices.exists_alias.go +++ /dev/null @@ -1,275 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesExistsAliasFunc(t Transport) IndicesExistsAlias { - return func(name []string, o ...func(*IndicesExistsAliasRequest)) (*Response, error) { - var r = IndicesExistsAliasRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesExistsAlias returns information about whether a particular alias exists. -// -// -type IndicesExistsAlias func(name []string, o ...func(*IndicesExistsAliasRequest)) (*Response, error) - -// IndicesExistsAliasRequest configures the Indices Exists Alias API request. -// -type IndicesExistsAliasRequest struct { - Index []string - - Name []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - Local *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesExistsAliasRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "HEAD" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_alias") + 1 + len(strings.Join(r.Name, ","))) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_alias") - path.WriteString("/") - path.WriteString(strings.Join(r.Name, ",")) - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesExistsAlias) WithContext(v context.Context) func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to filter aliases. -// -func (f IndicesExistsAlias) WithIndex(v ...string) func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesExistsAlias) WithAllowNoIndices(v bool) func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesExistsAlias) WithExpandWildcards(v string) func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesExistsAlias) WithIgnoreUnavailable(v bool) func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f IndicesExistsAlias) WithLocal(v bool) func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - r.Local = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesExistsAlias) WithPretty() func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesExistsAlias) WithHuman() func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesExistsAlias) WithErrorTrace() func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesExistsAlias) WithFilterPath(v ...string) func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesExistsAlias) WithHeader(h map[string]string) func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesExistsAlias) WithOpaqueID(s string) func(*IndicesExistsAliasRequest) { - return func(r *IndicesExistsAliasRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.exists_index_template.go b/opensearchapi/api.indices.exists_index_template.go deleted file mode 100644 index bcc501fd3..000000000 --- a/opensearchapi/api.indices.exists_index_template.go +++ /dev/null @@ -1,264 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesExistsIndexTemplateFunc(t Transport) IndicesExistsIndexTemplate { - return func(name string, o ...func(*IndicesExistsIndexTemplateRequest)) (*Response, error) { - var r = IndicesExistsIndexTemplateRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesExistsIndexTemplate returns information about whether a particular index template exists. -// -// -type IndicesExistsIndexTemplate func(name string, o ...func(*IndicesExistsIndexTemplateRequest)) (*Response, error) - -// IndicesExistsIndexTemplateRequest configures the Indices Exists Index Template API request. -// -type IndicesExistsIndexTemplateRequest struct { - Name string - - FlatSettings *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesExistsIndexTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "HEAD" - - path.Grow(1 + len("_index_template") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_index_template") - path.WriteString("/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesExistsIndexTemplate) WithContext(v context.Context) func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - r.ctx = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f IndicesExistsIndexTemplate) WithFlatSettings(v bool) func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - r.FlatSettings = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f IndicesExistsIndexTemplate) WithLocal(v bool) func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesExistsIndexTemplate) WithMasterTimeout(v time.Duration) func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesExistsIndexTemplate) WithClusterManagerTimeout(v time.Duration) func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesExistsIndexTemplate) WithPretty() func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesExistsIndexTemplate) WithHuman() func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesExistsIndexTemplate) WithErrorTrace() func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesExistsIndexTemplate) WithFilterPath(v ...string) func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesExistsIndexTemplate) WithHeader(h map[string]string) func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesExistsIndexTemplate) WithOpaqueID(s string) func(*IndicesExistsIndexTemplateRequest) { - return func(r *IndicesExistsIndexTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.exists_template.go b/opensearchapi/api.indices.exists_template.go deleted file mode 100644 index 322ff7a71..000000000 --- a/opensearchapi/api.indices.exists_template.go +++ /dev/null @@ -1,265 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use newIndicesExistsIndexTemplateFunc instead -func newIndicesExistsTemplateFunc(t Transport) IndicesExistsTemplate { - return func(name []string, o ...func(*IndicesExistsTemplateRequest)) (*Response, error) { - var r = IndicesExistsTemplateRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesExistsTemplate returns information about whether a particular index template exists. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -type IndicesExistsTemplate func(name []string, o ...func(*IndicesExistsTemplateRequest)) (*Response, error) - -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplateRequest instead -// IndicesExistsTemplateRequest configures the Indices Exists Template API request. -type IndicesExistsTemplateRequest struct { - Name []string - - FlatSettings *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplateRequest instead -func (r IndicesExistsTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "HEAD" - - path.Grow(1 + len("_template") + 1 + len(strings.Join(r.Name, ","))) - path.WriteString("/") - path.WriteString("_template") - path.WriteString("/") - path.WriteString(strings.Join(r.Name, ",")) - - params = make(map[string]string) - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithContext(v context.Context) func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - r.ctx = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithFlatSettings(v bool) func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - r.FlatSettings = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithLocal(v bool) func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithMasterTimeout(v time.Duration) func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithClusterManagerTimeout(v time.Duration) func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithPretty() func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithHuman() func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithErrorTrace() func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithFilterPath(v ...string) func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithHeader(h map[string]string) func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesExistsIndexTemplate instead -func (f IndicesExistsTemplate) WithOpaqueID(s string) func(*IndicesExistsTemplateRequest) { - return func(r *IndicesExistsTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.field_usage_stats.go b/opensearchapi/api.indices.field_usage_stats.go deleted file mode 100644 index 24577e35a..000000000 --- a/opensearchapi/api.indices.field_usage_stats.go +++ /dev/null @@ -1,263 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesFieldUsageStatsFunc(t Transport) IndicesFieldUsageStats { - return func(index string, o ...func(*IndicesFieldUsageStatsRequest)) (*Response, error) { - var r = IndicesFieldUsageStatsRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesFieldUsageStats returns the field usage stats for each field of an index -// -// This API is experimental. -// -// -type IndicesFieldUsageStats func(index string, o ...func(*IndicesFieldUsageStatsRequest)) (*Response, error) - -// IndicesFieldUsageStatsRequest configures the Indices Field Usage Stats API request. -// -type IndicesFieldUsageStatsRequest struct { - Index string - - AllowNoIndices *bool - ExpandWildcards string - Fields []string - IgnoreUnavailable *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesFieldUsageStatsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(r.Index) + 1 + len("_field_usage_stats")) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_field_usage_stats") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if len(r.Fields) > 0 { - params["fields"] = strings.Join(r.Fields, ",") - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesFieldUsageStats) WithContext(v context.Context) func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - r.ctx = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesFieldUsageStats) WithAllowNoIndices(v bool) func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesFieldUsageStats) WithExpandWildcards(v string) func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - r.ExpandWildcards = v - } -} - -// WithFields - a list of fields to include in the stats if only a subset of fields should be returned (supports wildcards). -// -func (f IndicesFieldUsageStats) WithFields(v ...string) func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - r.Fields = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesFieldUsageStats) WithIgnoreUnavailable(v bool) func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesFieldUsageStats) WithPretty() func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesFieldUsageStats) WithHuman() func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesFieldUsageStats) WithErrorTrace() func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesFieldUsageStats) WithFilterPath(v ...string) func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesFieldUsageStats) WithHeader(h map[string]string) func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesFieldUsageStats) WithOpaqueID(s string) func(*IndicesFieldUsageStatsRequest) { - return func(r *IndicesFieldUsageStatsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.flush.go b/opensearchapi/api.indices.flush.go deleted file mode 100644 index be820c853..000000000 --- a/opensearchapi/api.indices.flush.go +++ /dev/null @@ -1,284 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesFlushFunc(t Transport) IndicesFlush { - return func(o ...func(*IndicesFlushRequest)) (*Response, error) { - var r = IndicesFlushRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesFlush performs the flush operation on one or more indices. -// -// -type IndicesFlush func(o ...func(*IndicesFlushRequest)) (*Response, error) - -// IndicesFlushRequest configures the Indices Flush API request. -// -type IndicesFlushRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - Force *bool - IgnoreUnavailable *bool - WaitIfOngoing *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesFlushRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_flush")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_flush") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Force != nil { - params["force"] = strconv.FormatBool(*r.Force) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.WaitIfOngoing != nil { - params["wait_if_ongoing"] = strconv.FormatBool(*r.WaitIfOngoing) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesFlush) WithContext(v context.Context) func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all for all indices. -// -func (f IndicesFlush) WithIndex(v ...string) func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesFlush) WithAllowNoIndices(v bool) func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesFlush) WithExpandWildcards(v string) func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.ExpandWildcards = v - } -} - -// WithForce - whether a flush should be forced even if it is not necessarily needed ie. if no changes will be committed to the index. this is useful if transaction log ids should be incremented even if no uncommitted changes are present. (this setting can be considered as internal). -// -func (f IndicesFlush) WithForce(v bool) func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.Force = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesFlush) WithIgnoreUnavailable(v bool) func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithWaitIfOngoing - if set to true the flush operation will block until the flush can be executed if another flush operation is already executing. the default is true. if set to false the flush will be skipped iff if another flush operation is already running.. -// -func (f IndicesFlush) WithWaitIfOngoing(v bool) func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.WaitIfOngoing = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesFlush) WithPretty() func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesFlush) WithHuman() func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesFlush) WithErrorTrace() func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesFlush) WithFilterPath(v ...string) func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesFlush) WithHeader(h map[string]string) func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesFlush) WithOpaqueID(s string) func(*IndicesFlushRequest) { - return func(r *IndicesFlushRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.forcemerge.go b/opensearchapi/api.indices.forcemerge.go deleted file mode 100644 index 7fcd4ca53..000000000 --- a/opensearchapi/api.indices.forcemerge.go +++ /dev/null @@ -1,297 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesForcemergeFunc(t Transport) IndicesForcemerge { - return func(o ...func(*IndicesForcemergeRequest)) (*Response, error) { - var r = IndicesForcemergeRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesForcemerge performs the force merge operation on one or more indices. -// -// -type IndicesForcemerge func(o ...func(*IndicesForcemergeRequest)) (*Response, error) - -// IndicesForcemergeRequest configures the Indices Forcemerge API request. -// -type IndicesForcemergeRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - Flush *bool - IgnoreUnavailable *bool - MaxNumSegments *int - OnlyExpungeDeletes *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesForcemergeRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_forcemerge")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_forcemerge") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Flush != nil { - params["flush"] = strconv.FormatBool(*r.Flush) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.MaxNumSegments != nil { - params["max_num_segments"] = strconv.FormatInt(int64(*r.MaxNumSegments), 10) - } - - if r.OnlyExpungeDeletes != nil { - params["only_expunge_deletes"] = strconv.FormatBool(*r.OnlyExpungeDeletes) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesForcemerge) WithContext(v context.Context) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f IndicesForcemerge) WithIndex(v ...string) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesForcemerge) WithAllowNoIndices(v bool) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesForcemerge) WithExpandWildcards(v string) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.ExpandWildcards = v - } -} - -// WithFlush - specify whether the index should be flushed after performing the operation (default: true). -// -func (f IndicesForcemerge) WithFlush(v bool) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.Flush = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesForcemerge) WithIgnoreUnavailable(v bool) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithMaxNumSegments - the number of segments the index should be merged into (default: dynamic). -// -func (f IndicesForcemerge) WithMaxNumSegments(v int) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.MaxNumSegments = &v - } -} - -// WithOnlyExpungeDeletes - specify whether the operation should only expunge deleted documents. -// -func (f IndicesForcemerge) WithOnlyExpungeDeletes(v bool) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.OnlyExpungeDeletes = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesForcemerge) WithPretty() func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesForcemerge) WithHuman() func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesForcemerge) WithErrorTrace() func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesForcemerge) WithFilterPath(v ...string) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesForcemerge) WithHeader(h map[string]string) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesForcemerge) WithOpaqueID(s string) func(*IndicesForcemergeRequest) { - return func(r *IndicesForcemergeRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.get.go b/opensearchapi/api.indices.get.go deleted file mode 100644 index e9819bc46..000000000 --- a/opensearchapi/api.indices.get.go +++ /dev/null @@ -1,314 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesGetFunc(t Transport) IndicesGet { - return func(index []string, o ...func(*IndicesGetRequest)) (*Response, error) { - var r = IndicesGetRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesGet returns information about one or more indices. -// -// -type IndicesGet func(index []string, o ...func(*IndicesGetRequest)) (*Response, error) - -// IndicesGetRequest configures the Indices Get API request. -// -type IndicesGetRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - FlatSettings *bool - IgnoreUnavailable *bool - IncludeDefaults *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesGetRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(strings.Join(r.Index, ","))) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.IncludeDefaults != nil { - params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesGet) WithContext(v context.Context) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.ctx = v - } -} - -// WithAllowNoIndices - ignore if a wildcard expression resolves to no concrete indices (default: false). -// -func (f IndicesGet) WithAllowNoIndices(v bool) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether wildcard expressions should get expanded to open or closed indices (default: open). -// -func (f IndicesGet) WithExpandWildcards(v string) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.ExpandWildcards = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f IndicesGet) WithFlatSettings(v bool) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.FlatSettings = &v - } -} - -// WithIgnoreUnavailable - ignore unavailable indexes (default: false). -// -func (f IndicesGet) WithIgnoreUnavailable(v bool) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithIncludeDefaults - whether to return all default setting for each of the indices.. -// -func (f IndicesGet) WithIncludeDefaults(v bool) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.IncludeDefaults = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f IndicesGet) WithLocal(v bool) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesGet) WithMasterTimeout(v time.Duration) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesGet) WithClusterManagerTimeout(v time.Duration) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesGet) WithPretty() func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesGet) WithHuman() func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesGet) WithErrorTrace() func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesGet) WithFilterPath(v ...string) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesGet) WithHeader(h map[string]string) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesGet) WithOpaqueID(s string) func(*IndicesGetRequest) { - return func(r *IndicesGetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.get_alias.go b/opensearchapi/api.indices.get_alias.go deleted file mode 100644 index 38d4dcffc..000000000 --- a/opensearchapi/api.indices.get_alias.go +++ /dev/null @@ -1,285 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesGetAliasFunc(t Transport) IndicesGetAlias { - return func(o ...func(*IndicesGetAliasRequest)) (*Response, error) { - var r = IndicesGetAliasRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesGetAlias returns an alias. -// -// -type IndicesGetAlias func(o ...func(*IndicesGetAliasRequest)) (*Response, error) - -// IndicesGetAliasRequest configures the Indices Get Alias API request. -// -type IndicesGetAliasRequest struct { - Index []string - - Name []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - Local *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesGetAliasRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_alias") + 1 + len(strings.Join(r.Name, ","))) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_alias") - if len(r.Name) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Name, ",")) - } - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesGetAlias) WithContext(v context.Context) func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to filter aliases. -// -func (f IndicesGetAlias) WithIndex(v ...string) func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.Index = v - } -} - -// WithName - a list of alias names to return. -// -func (f IndicesGetAlias) WithName(v ...string) func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.Name = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesGetAlias) WithAllowNoIndices(v bool) func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesGetAlias) WithExpandWildcards(v string) func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesGetAlias) WithIgnoreUnavailable(v bool) func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f IndicesGetAlias) WithLocal(v bool) func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.Local = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesGetAlias) WithPretty() func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesGetAlias) WithHuman() func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesGetAlias) WithErrorTrace() func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesGetAlias) WithFilterPath(v ...string) func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesGetAlias) WithHeader(h map[string]string) func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesGetAlias) WithOpaqueID(s string) func(*IndicesGetAliasRequest) { - return func(r *IndicesGetAliasRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.get_datastream.go b/opensearchapi/api.indices.get_datastream.go deleted file mode 100644 index 7facf8b76..000000000 --- a/opensearchapi/api.indices.get_datastream.go +++ /dev/null @@ -1,198 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newIndicesGetDataStreamFunc(t Transport) IndicesGetDataStream { - return func(o ...func(*IndicesGetDataStreamRequest)) (*Response, error) { - var r = IndicesGetDataStreamRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesGetDataStream returns a data stream specific information if Name parameter is passed. Otherwise, returns all data streams. -type IndicesGetDataStream func(o ...func(*IndicesGetDataStreamRequest)) (*Response, error) - -// IndicesGetDataStreamRequest configures the Indices Get Data Stream API request. -type IndicesGetDataStreamRequest struct { - Name string - - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do execute the request and returns response or error. -func (r IndicesGetDataStreamRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_data_stream") + 1 + len(r.Name)) - path.WriteString("/_data_stream/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, nil -} - -// WithContext sets the request context. -func (f IndicesGetDataStream) WithContext(v context.Context) func(*IndicesGetDataStreamRequest) { - return func(r *IndicesGetDataStreamRequest) { - r.ctx = v - } -} - -// WithName - the comma separated names of the index templates. -func (f IndicesGetDataStream) WithName(v string) func(*IndicesGetDataStreamRequest) { - return func(r *IndicesGetDataStreamRequest) { - r.Name = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -func (f IndicesGetDataStream) WithClusterManagerTimeout(v time.Duration) func(*IndicesGetDataStreamRequest) { - return func(r *IndicesGetDataStreamRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -func (f IndicesGetDataStream) WithPretty() func(*IndicesGetDataStreamRequest) { - return func(r *IndicesGetDataStreamRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -func (f IndicesGetDataStream) WithHuman() func(*IndicesGetDataStreamRequest) { - return func(r *IndicesGetDataStreamRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -func (f IndicesGetDataStream) WithErrorTrace() func(*IndicesGetDataStreamRequest) { - return func(r *IndicesGetDataStreamRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -func (f IndicesGetDataStream) WithFilterPath(v ...string) func(*IndicesGetDataStreamRequest) { - return func(r *IndicesGetDataStreamRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -func (f IndicesGetDataStream) WithHeader(h map[string]string) func(*IndicesGetDataStreamRequest) { - return func(r *IndicesGetDataStreamRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -func (f IndicesGetDataStream) WithOpaqueID(s string) func(*IndicesGetDataStreamRequest) { - return func(r *IndicesGetDataStreamRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.get_datastream_stats.go b/opensearchapi/api.indices.get_datastream_stats.go deleted file mode 100644 index fe7dc318f..000000000 --- a/opensearchapi/api.indices.get_datastream_stats.go +++ /dev/null @@ -1,202 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newIndicesGetDataStreamStatsFunc(t Transport) IndicesGetDataStreamStats { - return func(o ...func(*IndicesGetDataStreamStatsRequest)) (*Response, error) { - var r = IndicesGetDataStreamStatsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesGetDataStreamStats returns a more insights about the data stream. -type IndicesGetDataStreamStats func(o ...func(*IndicesGetDataStreamStatsRequest)) (*Response, error) - -// IndicesGetDataStreamStatsRequest configures the Indices Get Data Stream Stats API request. -type IndicesGetDataStreamStatsRequest struct { - Name string - - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do execute the request and returns response or error. -func (r IndicesGetDataStreamStatsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_data_stream") + 1 + len(r.Name) + 1 + len("_stats")) - path.WriteString("/_data_stream") - if r.Name != "" { - path.WriteString("/") - path.WriteString(r.Name) - } - path.WriteString("/_stats") - - params = make(map[string]string) - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, nil -} - -// WithContext sets the request context. -func (f IndicesGetDataStreamStats) WithContext(v context.Context) func(*IndicesGetDataStreamStatsRequest) { - return func(r *IndicesGetDataStreamStatsRequest) { - r.ctx = v - } -} - -// WithName - the comma separated names of the index templates. -func (f IndicesGetDataStreamStats) WithName(v string) func(*IndicesGetDataStreamStatsRequest) { - return func(r *IndicesGetDataStreamStatsRequest) { - r.Name = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -func (f IndicesGetDataStreamStats) WithClusterManagerTimeout(v time.Duration) func(*IndicesGetDataStreamStatsRequest) { - return func(r *IndicesGetDataStreamStatsRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -func (f IndicesGetDataStreamStats) WithPretty() func(*IndicesGetDataStreamStatsRequest) { - return func(r *IndicesGetDataStreamStatsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -func (f IndicesGetDataStreamStats) WithHuman() func(*IndicesGetDataStreamStatsRequest) { - return func(r *IndicesGetDataStreamStatsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -func (f IndicesGetDataStreamStats) WithErrorTrace() func(*IndicesGetDataStreamStatsRequest) { - return func(r *IndicesGetDataStreamStatsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -func (f IndicesGetDataStreamStats) WithFilterPath(v ...string) func(*IndicesGetDataStreamStatsRequest) { - return func(r *IndicesGetDataStreamStatsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -func (f IndicesGetDataStreamStats) WithHeader(h map[string]string) func(*IndicesGetDataStreamStatsRequest) { - return func(r *IndicesGetDataStreamStatsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -func (f IndicesGetDataStreamStats) WithOpaqueID(s string) func(*IndicesGetDataStreamStatsRequest) { - return func(r *IndicesGetDataStreamStatsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.get_datastream_stats_test.go b/opensearchapi/api.indices.get_datastream_stats_test.go deleted file mode 100644 index 1285c6ca1..000000000 --- a/opensearchapi/api.indices.get_datastream_stats_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -package opensearchapi - -import ( - "context" - "fmt" - "net/http" - "testing" - - "github.com/stretchr/testify/require" -) - -type stubTransport struct { - req *http.Request -} - -func (t *stubTransport) Perform(req *http.Request) (*http.Response, error) { - t.req = req - return &http.Response{}, nil -} - -func TestIndicesGetDataStreamStatsRequest(t *testing.T) { - tt := stubTransport{} - req := IndicesGetDataStreamStatsRequest{} - - expectedPath := "/_data_stream/_stats" - - _, err := req.Do(context.Background(), &tt) - if err != nil { - t.Fatalf("Error getting response: %s", err) - } - - require.Equal(t, expectedPath, tt.req.URL.Path) -} - -func TestIndicesGetDataStreamStatsRequestOne(t *testing.T) { - tt := stubTransport{} - req := IndicesGetDataStreamStatsRequest{ - Name: "demo-1", - } - - expectedPath := fmt.Sprintf("/_data_stream/%s/_stats", req.Name) - - _, err := req.Do(context.Background(), &tt) - if err != nil { - t.Fatalf("Error getting response: %s", err) - } - - require.Equal(t, expectedPath, tt.req.URL.Path) -} diff --git a/opensearchapi/api.indices.get_field_mapping.go b/opensearchapi/api.indices.get_field_mapping.go deleted file mode 100644 index fb161ea10..000000000 --- a/opensearchapi/api.indices.get_field_mapping.go +++ /dev/null @@ -1,290 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesGetFieldMappingFunc(t Transport) IndicesGetFieldMapping { - return func(fields []string, o ...func(*IndicesGetFieldMappingRequest)) (*Response, error) { - var r = IndicesGetFieldMappingRequest{Fields: fields} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesGetFieldMapping returns mapping for one or more fields. -// -// -type IndicesGetFieldMapping func(fields []string, o ...func(*IndicesGetFieldMappingRequest)) (*Response, error) - -// IndicesGetFieldMappingRequest configures the Indices Get Field Mapping API request. -// -type IndicesGetFieldMappingRequest struct { - Index []string - - Fields []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - IncludeDefaults *bool - Local *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesGetFieldMappingRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_mapping") + 1 + len("field") + 1 + len(strings.Join(r.Fields, ","))) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_mapping") - path.WriteString("/") - path.WriteString("field") - path.WriteString("/") - path.WriteString(strings.Join(r.Fields, ",")) - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.IncludeDefaults != nil { - params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesGetFieldMapping) WithContext(v context.Context) func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names. -// -func (f IndicesGetFieldMapping) WithIndex(v ...string) func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesGetFieldMapping) WithAllowNoIndices(v bool) func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesGetFieldMapping) WithExpandWildcards(v string) func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesGetFieldMapping) WithIgnoreUnavailable(v bool) func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithIncludeDefaults - whether the default mapping values should be returned as well. -// -func (f IndicesGetFieldMapping) WithIncludeDefaults(v bool) func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.IncludeDefaults = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f IndicesGetFieldMapping) WithLocal(v bool) func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.Local = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesGetFieldMapping) WithPretty() func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesGetFieldMapping) WithHuman() func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesGetFieldMapping) WithErrorTrace() func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesGetFieldMapping) WithFilterPath(v ...string) func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesGetFieldMapping) WithHeader(h map[string]string) func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesGetFieldMapping) WithOpaqueID(s string) func(*IndicesGetFieldMappingRequest) { - return func(r *IndicesGetFieldMappingRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.get_index_template.go b/opensearchapi/api.indices.get_index_template.go deleted file mode 100644 index 6ad216813..000000000 --- a/opensearchapi/api.indices.get_index_template.go +++ /dev/null @@ -1,274 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesGetIndexTemplateFunc(t Transport) IndicesGetIndexTemplate { - return func(o ...func(*IndicesGetIndexTemplateRequest)) (*Response, error) { - var r = IndicesGetIndexTemplateRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesGetIndexTemplate returns an index template. -// -// -type IndicesGetIndexTemplate func(o ...func(*IndicesGetIndexTemplateRequest)) (*Response, error) - -// IndicesGetIndexTemplateRequest configures the Indices Get Index Template API request. -// -type IndicesGetIndexTemplateRequest struct { - Name []string - - FlatSettings *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesGetIndexTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_index_template") + 1 + len(strings.Join(r.Name, ","))) - path.WriteString("/") - path.WriteString("_index_template") - if len(r.Name) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Name, ",")) - } - - params = make(map[string]string) - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesGetIndexTemplate) WithContext(v context.Context) func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - r.ctx = v - } -} - -// WithName - the comma separated names of the index templates. -// -func (f IndicesGetIndexTemplate) WithName(v ...string) func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - r.Name = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f IndicesGetIndexTemplate) WithFlatSettings(v bool) func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - r.FlatSettings = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f IndicesGetIndexTemplate) WithLocal(v bool) func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesGetIndexTemplate) WithMasterTimeout(v time.Duration) func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesGetIndexTemplate) WithClusterManagerTimeout(v time.Duration) func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesGetIndexTemplate) WithPretty() func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesGetIndexTemplate) WithHuman() func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesGetIndexTemplate) WithErrorTrace() func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesGetIndexTemplate) WithFilterPath(v ...string) func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesGetIndexTemplate) WithHeader(h map[string]string) func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesGetIndexTemplate) WithOpaqueID(s string) func(*IndicesGetIndexTemplateRequest) { - return func(r *IndicesGetIndexTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.get_mapping.go b/opensearchapi/api.indices.get_mapping.go deleted file mode 100644 index 716640dbc..000000000 --- a/opensearchapi/api.indices.get_mapping.go +++ /dev/null @@ -1,299 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesGetMappingFunc(t Transport) IndicesGetMapping { - return func(o ...func(*IndicesGetMappingRequest)) (*Response, error) { - var r = IndicesGetMappingRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesGetMapping returns mappings for one or more indices. -// -// -type IndicesGetMapping func(o ...func(*IndicesGetMappingRequest)) (*Response, error) - -// IndicesGetMappingRequest configures the Indices Get Mapping API request. -// -type IndicesGetMappingRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesGetMappingRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_mapping")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_mapping") - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesGetMapping) WithContext(v context.Context) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names. -// -func (f IndicesGetMapping) WithIndex(v ...string) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesGetMapping) WithAllowNoIndices(v bool) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesGetMapping) WithExpandWildcards(v string) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesGetMapping) WithIgnoreUnavailable(v bool) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f IndicesGetMapping) WithLocal(v bool) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesGetMapping) WithMasterTimeout(v time.Duration) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesGetMapping) WithClusterManagerTimeout(v time.Duration) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesGetMapping) WithPretty() func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesGetMapping) WithHuman() func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesGetMapping) WithErrorTrace() func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesGetMapping) WithFilterPath(v ...string) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesGetMapping) WithHeader(h map[string]string) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesGetMapping) WithOpaqueID(s string) func(*IndicesGetMappingRequest) { - return func(r *IndicesGetMappingRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.get_settings.go b/opensearchapi/api.indices.get_settings.go deleted file mode 100644 index d97b110c6..000000000 --- a/opensearchapi/api.indices.get_settings.go +++ /dev/null @@ -1,340 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesGetSettingsFunc(t Transport) IndicesGetSettings { - return func(o ...func(*IndicesGetSettingsRequest)) (*Response, error) { - var r = IndicesGetSettingsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesGetSettings returns settings for one or more indices. -// -// -type IndicesGetSettings func(o ...func(*IndicesGetSettingsRequest)) (*Response, error) - -// IndicesGetSettingsRequest configures the Indices Get Settings API request. -// -type IndicesGetSettingsRequest struct { - Index []string - - Name []string - - AllowNoIndices *bool - ExpandWildcards string - FlatSettings *bool - IgnoreUnavailable *bool - IncludeDefaults *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesGetSettingsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_settings") + 1 + len(strings.Join(r.Name, ","))) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_settings") - if len(r.Name) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Name, ",")) - } - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.IncludeDefaults != nil { - params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesGetSettings) WithContext(v context.Context) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f IndicesGetSettings) WithIndex(v ...string) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.Index = v - } -} - -// WithName - the name of the settings that should be included. -// -func (f IndicesGetSettings) WithName(v ...string) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.Name = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesGetSettings) WithAllowNoIndices(v bool) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesGetSettings) WithExpandWildcards(v string) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.ExpandWildcards = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f IndicesGetSettings) WithFlatSettings(v bool) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.FlatSettings = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesGetSettings) WithIgnoreUnavailable(v bool) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithIncludeDefaults - whether to return all default setting for each of the indices.. -// -func (f IndicesGetSettings) WithIncludeDefaults(v bool) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.IncludeDefaults = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f IndicesGetSettings) WithLocal(v bool) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesGetSettings) WithMasterTimeout(v time.Duration) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesGetSettings) WithClusterManagerTimeout(v time.Duration) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesGetSettings) WithPretty() func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesGetSettings) WithHuman() func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesGetSettings) WithErrorTrace() func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesGetSettings) WithFilterPath(v ...string) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesGetSettings) WithHeader(h map[string]string) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesGetSettings) WithOpaqueID(s string) func(*IndicesGetSettingsRequest) { - return func(r *IndicesGetSettingsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.get_template.go b/opensearchapi/api.indices.get_template.go deleted file mode 100644 index cd97d8cb3..000000000 --- a/opensearchapi/api.indices.get_template.go +++ /dev/null @@ -1,278 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use newIndicesGetIndexTemplateFunc instead - -func newIndicesGetTemplateFunc(t Transport) IndicesGetTemplate { - return func(o ...func(*IndicesGetTemplateRequest)) (*Response, error) { - var r = IndicesGetTemplateRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesGetTemplate returns an index template. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -type IndicesGetTemplate func(o ...func(*IndicesGetTemplateRequest)) (*Response, error) - -// IndicesGetTemplateRequest configures the Indices Get Template API request. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplateRequest instead -type IndicesGetTemplateRequest struct { - Name []string - - FlatSettings *bool - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplateRequest instead -func (r IndicesGetTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_template") + 1 + len(strings.Join(r.Name, ","))) - path.WriteString("/") - path.WriteString("_template") - if len(r.Name) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Name, ",")) - } - - params = make(map[string]string) - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithContext(v context.Context) func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - r.ctx = v - } -} - -// WithName - the comma separated names of the index templates. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithName(v ...string) func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - r.Name = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithFlatSettings(v bool) func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - r.FlatSettings = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithLocal(v bool) func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithMasterTimeout(v time.Duration) func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithClusterManagerTimeout(v time.Duration) func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithPretty() func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithHuman() func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithErrorTrace() func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithFilterPath(v ...string) func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithHeader(h map[string]string) func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesGetIndexTemplate instead -func (f IndicesGetTemplate) WithOpaqueID(s string) func(*IndicesGetTemplateRequest) { - return func(r *IndicesGetTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.get_upgrade.go b/opensearchapi/api.indices.get_upgrade.go deleted file mode 100644 index 04fb22272..000000000 --- a/opensearchapi/api.indices.get_upgrade.go +++ /dev/null @@ -1,258 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesGetUpgradeFunc(t Transport) IndicesGetUpgrade { - return func(o ...func(*IndicesGetUpgradeRequest)) (*Response, error) { - var r = IndicesGetUpgradeRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesGetUpgrade deprecated Returns a progress status of current upgrade. -// -// -type IndicesGetUpgrade func(o ...func(*IndicesGetUpgradeRequest)) (*Response, error) - -// IndicesGetUpgradeRequest configures the Indices Get Upgrade API request. -// -type IndicesGetUpgradeRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesGetUpgradeRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_upgrade")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_upgrade") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesGetUpgrade) WithContext(v context.Context) func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f IndicesGetUpgrade) WithIndex(v ...string) func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesGetUpgrade) WithAllowNoIndices(v bool) func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesGetUpgrade) WithExpandWildcards(v string) func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesGetUpgrade) WithIgnoreUnavailable(v bool) func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesGetUpgrade) WithPretty() func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesGetUpgrade) WithHuman() func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesGetUpgrade) WithErrorTrace() func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesGetUpgrade) WithFilterPath(v ...string) func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesGetUpgrade) WithHeader(h map[string]string) func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesGetUpgrade) WithOpaqueID(s string) func(*IndicesGetUpgradeRequest) { - return func(r *IndicesGetUpgradeRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.open.go b/opensearchapi/api.indices.open.go deleted file mode 100644 index e444d34e4..000000000 --- a/opensearchapi/api.indices.open.go +++ /dev/null @@ -1,303 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesOpenFunc(t Transport) IndicesOpen { - return func(index []string, o ...func(*IndicesOpenRequest)) (*Response, error) { - var r = IndicesOpenRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesOpen opens an index. -// -// -type IndicesOpen func(index []string, o ...func(*IndicesOpenRequest)) (*Response, error) - -// IndicesOpenRequest configures the Indices Open API request. -// -type IndicesOpenRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesOpenRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_open")) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - path.WriteString("/") - path.WriteString("_open") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesOpen) WithContext(v context.Context) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.ctx = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesOpen) WithAllowNoIndices(v bool) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesOpen) WithExpandWildcards(v string) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesOpen) WithIgnoreUnavailable(v bool) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesOpen) WithMasterTimeout(v time.Duration) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesOpen) WithClusterManagerTimeout(v time.Duration) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesOpen) WithTimeout(v time.Duration) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - sets the number of active shards to wait for before the operation returns.. -// -func (f IndicesOpen) WithWaitForActiveShards(v string) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesOpen) WithPretty() func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesOpen) WithHuman() func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesOpen) WithErrorTrace() func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesOpen) WithFilterPath(v ...string) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesOpen) WithHeader(h map[string]string) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesOpen) WithOpaqueID(s string) func(*IndicesOpenRequest) { - return func(r *IndicesOpenRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.put_alias.go b/opensearchapi/api.indices.put_alias.go deleted file mode 100644 index f0504befd..000000000 --- a/opensearchapi/api.indices.put_alias.go +++ /dev/null @@ -1,269 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" - "time" -) - -func newIndicesPutAliasFunc(t Transport) IndicesPutAlias { - return func(index []string, name string, o ...func(*IndicesPutAliasRequest)) (*Response, error) { - var r = IndicesPutAliasRequest{Index: index, Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesPutAlias creates or updates an alias. -// -// -type IndicesPutAlias func(index []string, name string, o ...func(*IndicesPutAliasRequest)) (*Response, error) - -// IndicesPutAliasRequest configures the Indices Put Alias API request. -// -type IndicesPutAliasRequest struct { - Index []string - - Body io.Reader - - Name string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesPutAliasRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_aliases") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - path.WriteString("/") - path.WriteString("_aliases") - path.WriteString("/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesPutAlias) WithContext(v context.Context) func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - r.ctx = v - } -} - -// WithBody - The settings for the alias, such as `routing` or `filter`. -// -func (f IndicesPutAlias) WithBody(v io.Reader) func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - r.Body = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesPutAlias) WithMasterTimeout(v time.Duration) func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesPutAlias) WithClusterManagerTimeout(v time.Duration) func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit timestamp for the document. -// -func (f IndicesPutAlias) WithTimeout(v time.Duration) func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesPutAlias) WithPretty() func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesPutAlias) WithHuman() func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesPutAlias) WithErrorTrace() func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesPutAlias) WithFilterPath(v ...string) func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesPutAlias) WithHeader(h map[string]string) func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesPutAlias) WithOpaqueID(s string) func(*IndicesPutAliasRequest) { - return func(r *IndicesPutAliasRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.put_index_template.go b/opensearchapi/api.indices.put_index_template.go deleted file mode 100644 index 2ce88379e..000000000 --- a/opensearchapi/api.indices.put_index_template.go +++ /dev/null @@ -1,271 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesPutIndexTemplateFunc(t Transport) IndicesPutIndexTemplate { - return func(name string, body io.Reader, o ...func(*IndicesPutIndexTemplateRequest)) (*Response, error) { - var r = IndicesPutIndexTemplateRequest{Name: name, Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesPutIndexTemplate creates or updates an index template. -// -// -type IndicesPutIndexTemplate func(name string, body io.Reader, o ...func(*IndicesPutIndexTemplateRequest)) (*Response, error) - -// IndicesPutIndexTemplateRequest configures the Indices Put Index Template API request. -// -type IndicesPutIndexTemplateRequest struct { - Body io.Reader - - Name string - - Cause string - Create *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesPutIndexTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len("_index_template") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_index_template") - path.WriteString("/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.Cause != "" { - params["cause"] = r.Cause - } - - if r.Create != nil { - params["create"] = strconv.FormatBool(*r.Create) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesPutIndexTemplate) WithContext(v context.Context) func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - r.ctx = v - } -} - -// WithCause - user defined reason for creating/updating the index template. -// -func (f IndicesPutIndexTemplate) WithCause(v string) func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - r.Cause = v - } -} - -// WithCreate - whether the index template should only be added if new or can also replace an existing one. -// -func (f IndicesPutIndexTemplate) WithCreate(v bool) func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - r.Create = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesPutIndexTemplate) WithMasterTimeout(v time.Duration) func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesPutIndexTemplate) WithClusterManagerTimeout(v time.Duration) func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesPutIndexTemplate) WithPretty() func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesPutIndexTemplate) WithHuman() func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesPutIndexTemplate) WithErrorTrace() func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesPutIndexTemplate) WithFilterPath(v ...string) func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesPutIndexTemplate) WithHeader(h map[string]string) func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesPutIndexTemplate) WithOpaqueID(s string) func(*IndicesPutIndexTemplateRequest) { - return func(r *IndicesPutIndexTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.put_mapping.go b/opensearchapi/api.indices.put_mapping.go deleted file mode 100644 index d1f09c3f7..000000000 --- a/opensearchapi/api.indices.put_mapping.go +++ /dev/null @@ -1,320 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesPutMappingFunc(t Transport) IndicesPutMapping { - return func(body io.Reader, o ...func(*IndicesPutMappingRequest)) (*Response, error) { - var r = IndicesPutMappingRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesPutMapping updates the index mappings. -// -// -type IndicesPutMapping func(body io.Reader, o ...func(*IndicesPutMappingRequest)) (*Response, error) - -// IndicesPutMappingRequest configures the Indices Put Mapping API request. -// -type IndicesPutMappingRequest struct { - Index []string - - Body io.Reader - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - WriteIndexOnly *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesPutMappingRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(len(strings.Join(r.Index, ",")) + len("/_mapping") + 1) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_mapping") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WriteIndexOnly != nil { - params["write_index_only"] = strconv.FormatBool(*r.WriteIndexOnly) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesPutMapping) WithContext(v context.Context) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.. -// -func (f IndicesPutMapping) WithIndex(v ...string) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesPutMapping) WithAllowNoIndices(v bool) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesPutMapping) WithExpandWildcards(v string) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesPutMapping) WithIgnoreUnavailable(v bool) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesPutMapping) WithMasterTimeout(v time.Duration) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesPutMapping) WithClusterManagerTimeout(v time.Duration) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesPutMapping) WithTimeout(v time.Duration) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.Timeout = v - } -} - -// WithWriteIndexOnly - when true, applies mappings only to the write index of an alias or data stream. -// -func (f IndicesPutMapping) WithWriteIndexOnly(v bool) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.WriteIndexOnly = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesPutMapping) WithPretty() func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesPutMapping) WithHuman() func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesPutMapping) WithErrorTrace() func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesPutMapping) WithFilterPath(v ...string) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesPutMapping) WithHeader(h map[string]string) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesPutMapping) WithOpaqueID(s string) func(*IndicesPutMappingRequest) { - return func(r *IndicesPutMappingRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.put_settings.go b/opensearchapi/api.indices.put_settings.go deleted file mode 100644 index 370fa3199..000000000 --- a/opensearchapi/api.indices.put_settings.go +++ /dev/null @@ -1,333 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesPutSettingsFunc(t Transport) IndicesPutSettings { - return func(body io.Reader, o ...func(*IndicesPutSettingsRequest)) (*Response, error) { - var r = IndicesPutSettingsRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesPutSettings updates the index settings. -// -// -type IndicesPutSettings func(body io.Reader, o ...func(*IndicesPutSettingsRequest)) (*Response, error) - -// IndicesPutSettingsRequest configures the Indices Put Settings API request. -// -type IndicesPutSettingsRequest struct { - Index []string - - Body io.Reader - - AllowNoIndices *bool - ExpandWildcards string - FlatSettings *bool - IgnoreUnavailable *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - PreserveExisting *bool - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesPutSettingsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_settings")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_settings") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.PreserveExisting != nil { - params["preserve_existing"] = strconv.FormatBool(*r.PreserveExisting) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesPutSettings) WithContext(v context.Context) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f IndicesPutSettings) WithIndex(v ...string) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesPutSettings) WithAllowNoIndices(v bool) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesPutSettings) WithExpandWildcards(v string) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.ExpandWildcards = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f IndicesPutSettings) WithFlatSettings(v bool) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.FlatSettings = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesPutSettings) WithIgnoreUnavailable(v bool) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesPutSettings) WithMasterTimeout(v time.Duration) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesPutSettings) WithClusterManagerTimeout(v time.Duration) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPreserveExisting - whether to update existing settings. if set to `true` existing settings on an index remain unchanged, the default is `false`. -// -func (f IndicesPutSettings) WithPreserveExisting(v bool) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.PreserveExisting = &v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesPutSettings) WithTimeout(v time.Duration) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesPutSettings) WithPretty() func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesPutSettings) WithHuman() func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesPutSettings) WithErrorTrace() func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesPutSettings) WithFilterPath(v ...string) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesPutSettings) WithHeader(h map[string]string) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesPutSettings) WithOpaqueID(s string) func(*IndicesPutSettingsRequest) { - return func(r *IndicesPutSettingsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.put_template.go b/opensearchapi/api.indices.put_template.go deleted file mode 100644 index f747bce6f..000000000 --- a/opensearchapi/api.indices.put_template.go +++ /dev/null @@ -1,270 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use newIndicesPutIndexTemplateFunc instead -func newIndicesPutTemplateFunc(t Transport) IndicesPutTemplate { - return func(name string, body io.Reader, o ...func(*IndicesPutTemplateRequest)) (*Response, error) { - var r = IndicesPutTemplateRequest{Name: name, Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesPutTemplate creates or updates an index template. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -type IndicesPutTemplate func(name string, body io.Reader, o ...func(*IndicesPutTemplateRequest)) (*Response, error) - -// IndicesPutTemplateRequest configures the Indices Put Template API request. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettingsRequest instead -type IndicesPutTemplateRequest struct { - Body io.Reader - - Name string - - Create *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Order *int - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettingsRequest instead -func (r IndicesPutTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len("_template") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_template") - path.WriteString("/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.Create != nil { - params["create"] = strconv.FormatBool(*r.Create) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Order != nil { - params["order"] = strconv.FormatInt(int64(*r.Order), 10) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithContext(v context.Context) func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - r.ctx = v - } -} - -// WithCreate - whether the index template should only be added if new or can also replace an existing one. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithCreate(v bool) func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - r.Create = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithMasterTimeout(v time.Duration) func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithClusterManagerTimeout(v time.Duration) func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithOrder - the order for this template when merging multiple matching ones (higher numbers are merged later, overriding the lower numbers). -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithOrder(v int) func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - r.Order = &v - } -} - -// WithPretty makes the response body pretty-printed. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithPretty() func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithHuman() func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithErrorTrace() func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithFilterPath(v ...string) func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithHeader(h map[string]string) func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndicesPutSettings instead -func (f IndicesPutTemplate) WithOpaqueID(s string) func(*IndicesPutTemplateRequest) { - return func(r *IndicesPutTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.recovery.go b/opensearchapi/api.indices.recovery.go deleted file mode 100644 index c0e636aba..000000000 --- a/opensearchapi/api.indices.recovery.go +++ /dev/null @@ -1,245 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesRecoveryFunc(t Transport) IndicesRecovery { - return func(o ...func(*IndicesRecoveryRequest)) (*Response, error) { - var r = IndicesRecoveryRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesRecovery returns information about ongoing index shard recoveries. -// -// -type IndicesRecovery func(o ...func(*IndicesRecoveryRequest)) (*Response, error) - -// IndicesRecoveryRequest configures the Indices Recovery API request. -// -type IndicesRecoveryRequest struct { - Index []string - - ActiveOnly *bool - Detailed *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesRecoveryRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_recovery")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_recovery") - - params = make(map[string]string) - - if r.ActiveOnly != nil { - params["active_only"] = strconv.FormatBool(*r.ActiveOnly) - } - - if r.Detailed != nil { - params["detailed"] = strconv.FormatBool(*r.Detailed) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesRecovery) WithContext(v context.Context) func(*IndicesRecoveryRequest) { - return func(r *IndicesRecoveryRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f IndicesRecovery) WithIndex(v ...string) func(*IndicesRecoveryRequest) { - return func(r *IndicesRecoveryRequest) { - r.Index = v - } -} - -// WithActiveOnly - display only those recoveries that are currently on-going. -// -func (f IndicesRecovery) WithActiveOnly(v bool) func(*IndicesRecoveryRequest) { - return func(r *IndicesRecoveryRequest) { - r.ActiveOnly = &v - } -} - -// WithDetailed - whether to display detailed information about shard recovery. -// -func (f IndicesRecovery) WithDetailed(v bool) func(*IndicesRecoveryRequest) { - return func(r *IndicesRecoveryRequest) { - r.Detailed = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesRecovery) WithPretty() func(*IndicesRecoveryRequest) { - return func(r *IndicesRecoveryRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesRecovery) WithHuman() func(*IndicesRecoveryRequest) { - return func(r *IndicesRecoveryRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesRecovery) WithErrorTrace() func(*IndicesRecoveryRequest) { - return func(r *IndicesRecoveryRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesRecovery) WithFilterPath(v ...string) func(*IndicesRecoveryRequest) { - return func(r *IndicesRecoveryRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesRecovery) WithHeader(h map[string]string) func(*IndicesRecoveryRequest) { - return func(r *IndicesRecoveryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesRecovery) WithOpaqueID(s string) func(*IndicesRecoveryRequest) { - return func(r *IndicesRecoveryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.refresh.go b/opensearchapi/api.indices.refresh.go deleted file mode 100644 index 4cd2dc6c4..000000000 --- a/opensearchapi/api.indices.refresh.go +++ /dev/null @@ -1,258 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesRefreshFunc(t Transport) IndicesRefresh { - return func(o ...func(*IndicesRefreshRequest)) (*Response, error) { - var r = IndicesRefreshRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesRefresh performs the refresh operation in one or more indices. -// -// -type IndicesRefresh func(o ...func(*IndicesRefreshRequest)) (*Response, error) - -// IndicesRefreshRequest configures the Indices Refresh API request. -// -type IndicesRefreshRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesRefreshRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_refresh")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_refresh") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesRefresh) WithContext(v context.Context) func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f IndicesRefresh) WithIndex(v ...string) func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesRefresh) WithAllowNoIndices(v bool) func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesRefresh) WithExpandWildcards(v string) func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesRefresh) WithIgnoreUnavailable(v bool) func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesRefresh) WithPretty() func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesRefresh) WithHuman() func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesRefresh) WithErrorTrace() func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesRefresh) WithFilterPath(v ...string) func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesRefresh) WithHeader(h map[string]string) func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesRefresh) WithOpaqueID(s string) func(*IndicesRefreshRequest) { - return func(r *IndicesRefreshRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.resolve_index.go b/opensearchapi/api.indices.resolve_index.go deleted file mode 100644 index 2678e0fe6..000000000 --- a/opensearchapi/api.indices.resolve_index.go +++ /dev/null @@ -1,225 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" -) - -func newIndicesResolveIndexFunc(t Transport) IndicesResolveIndex { - return func(name []string, o ...func(*IndicesResolveIndexRequest)) (*Response, error) { - var r = IndicesResolveIndexRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesResolveIndex returns information about any matching indices, aliases, and data streams -// -// This API is experimental. -// -// -type IndicesResolveIndex func(name []string, o ...func(*IndicesResolveIndexRequest)) (*Response, error) - -// IndicesResolveIndexRequest configures the Indices Resolve Index API request. -// -type IndicesResolveIndexRequest struct { - Name []string - - ExpandWildcards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesResolveIndexRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_resolve") + 1 + len("index") + 1 + len(strings.Join(r.Name, ","))) - path.WriteString("/") - path.WriteString("_resolve") - path.WriteString("/") - path.WriteString("index") - path.WriteString("/") - path.WriteString(strings.Join(r.Name, ",")) - - params = make(map[string]string) - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesResolveIndex) WithContext(v context.Context) func(*IndicesResolveIndexRequest) { - return func(r *IndicesResolveIndexRequest) { - r.ctx = v - } -} - -// WithExpandWildcards - whether wildcard expressions should get expanded to open or closed indices (default: open). -// -func (f IndicesResolveIndex) WithExpandWildcards(v string) func(*IndicesResolveIndexRequest) { - return func(r *IndicesResolveIndexRequest) { - r.ExpandWildcards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesResolveIndex) WithPretty() func(*IndicesResolveIndexRequest) { - return func(r *IndicesResolveIndexRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesResolveIndex) WithHuman() func(*IndicesResolveIndexRequest) { - return func(r *IndicesResolveIndexRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesResolveIndex) WithErrorTrace() func(*IndicesResolveIndexRequest) { - return func(r *IndicesResolveIndexRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesResolveIndex) WithFilterPath(v ...string) func(*IndicesResolveIndexRequest) { - return func(r *IndicesResolveIndexRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesResolveIndex) WithHeader(h map[string]string) func(*IndicesResolveIndexRequest) { - return func(r *IndicesResolveIndexRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesResolveIndex) WithOpaqueID(s string) func(*IndicesResolveIndexRequest) { - return func(r *IndicesResolveIndexRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.rollover.go b/opensearchapi/api.indices.rollover.go deleted file mode 100644 index 3b291b476..000000000 --- a/opensearchapi/api.indices.rollover.go +++ /dev/null @@ -1,306 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesRolloverFunc(t Transport) IndicesRollover { - return func(alias string, o ...func(*IndicesRolloverRequest)) (*Response, error) { - var r = IndicesRolloverRequest{Alias: alias} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesRollover updates an alias to point to a new index when the existing index -// is considered to be too large or too old. -// -// -type IndicesRollover func(alias string, o ...func(*IndicesRolloverRequest)) (*Response, error) - -// IndicesRolloverRequest configures the Indices Rollover API request. -// -type IndicesRolloverRequest struct { - Body io.Reader - - Alias string - NewIndex string - - DryRun *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesRolloverRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(r.Alias) + 1 + len("_rollover") + 1 + len(r.NewIndex)) - path.WriteString("/") - path.WriteString(r.Alias) - path.WriteString("/") - path.WriteString("_rollover") - if r.NewIndex != "" { - path.WriteString("/") - path.WriteString(r.NewIndex) - } - - params = make(map[string]string) - - if r.DryRun != nil { - params["dry_run"] = strconv.FormatBool(*r.DryRun) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesRollover) WithContext(v context.Context) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.ctx = v - } -} - -// WithBody - The conditions that needs to be met for executing rollover. -// -func (f IndicesRollover) WithBody(v io.Reader) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.Body = v - } -} - -// WithNewIndex - the name of the rollover index. -// -func (f IndicesRollover) WithNewIndex(v string) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.NewIndex = v - } -} - -// WithDryRun - if set to true the rollover action will only be validated but not actually performed even if a condition matches. the default is false. -// -func (f IndicesRollover) WithDryRun(v bool) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.DryRun = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesRollover) WithMasterTimeout(v time.Duration) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesRollover) WithClusterManagerTimeout(v time.Duration) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesRollover) WithTimeout(v time.Duration) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - set the number of active shards to wait for on the newly created rollover index before the operation returns.. -// -func (f IndicesRollover) WithWaitForActiveShards(v string) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesRollover) WithPretty() func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesRollover) WithHuman() func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesRollover) WithErrorTrace() func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesRollover) WithFilterPath(v ...string) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesRollover) WithHeader(h map[string]string) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesRollover) WithOpaqueID(s string) func(*IndicesRolloverRequest) { - return func(r *IndicesRolloverRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.segments.go b/opensearchapi/api.indices.segments.go deleted file mode 100644 index 0ac272382..000000000 --- a/opensearchapi/api.indices.segments.go +++ /dev/null @@ -1,271 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesSegmentsFunc(t Transport) IndicesSegments { - return func(o ...func(*IndicesSegmentsRequest)) (*Response, error) { - var r = IndicesSegmentsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesSegments provides low-level information about segments in a Lucene index. -// -// -type IndicesSegments func(o ...func(*IndicesSegmentsRequest)) (*Response, error) - -// IndicesSegmentsRequest configures the Indices Segments API request. -// -type IndicesSegmentsRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - Verbose *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesSegmentsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_segments")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_segments") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Verbose != nil { - params["verbose"] = strconv.FormatBool(*r.Verbose) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesSegments) WithContext(v context.Context) func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f IndicesSegments) WithIndex(v ...string) func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesSegments) WithAllowNoIndices(v bool) func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesSegments) WithExpandWildcards(v string) func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesSegments) WithIgnoreUnavailable(v bool) func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithVerbose - includes detailed memory usage by lucene.. -// -func (f IndicesSegments) WithVerbose(v bool) func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - r.Verbose = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesSegments) WithPretty() func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesSegments) WithHuman() func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesSegments) WithErrorTrace() func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesSegments) WithFilterPath(v ...string) func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesSegments) WithHeader(h map[string]string) func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesSegments) WithOpaqueID(s string) func(*IndicesSegmentsRequest) { - return func(r *IndicesSegmentsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.shard_stores.go b/opensearchapi/api.indices.shard_stores.go deleted file mode 100644 index 8e6bb57f7..000000000 --- a/opensearchapi/api.indices.shard_stores.go +++ /dev/null @@ -1,271 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesShardStoresFunc(t Transport) IndicesShardStores { - return func(o ...func(*IndicesShardStoresRequest)) (*Response, error) { - var r = IndicesShardStoresRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesShardStores provides store information for shard copies of indices. -// -// -type IndicesShardStores func(o ...func(*IndicesShardStoresRequest)) (*Response, error) - -// IndicesShardStoresRequest configures the Indices Shard Stores API request. -// -type IndicesShardStoresRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - Status []string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesShardStoresRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_shard_stores")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_shard_stores") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if len(r.Status) > 0 { - params["status"] = strings.Join(r.Status, ",") - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesShardStores) WithContext(v context.Context) func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f IndicesShardStores) WithIndex(v ...string) func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesShardStores) WithAllowNoIndices(v bool) func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesShardStores) WithExpandWildcards(v string) func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesShardStores) WithIgnoreUnavailable(v bool) func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithStatus - a list of statuses used to filter on shards to get store information for. -// -func (f IndicesShardStores) WithStatus(v ...string) func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - r.Status = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesShardStores) WithPretty() func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesShardStores) WithHuman() func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesShardStores) WithErrorTrace() func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesShardStores) WithFilterPath(v ...string) func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesShardStores) WithHeader(h map[string]string) func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesShardStores) WithOpaqueID(s string) func(*IndicesShardStoresRequest) { - return func(r *IndicesShardStoresRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.shrink.go b/opensearchapi/api.indices.shrink.go deleted file mode 100644 index 685cf6b25..000000000 --- a/opensearchapi/api.indices.shrink.go +++ /dev/null @@ -1,296 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesShrinkFunc(t Transport) IndicesShrink { - return func(index string, target string, o ...func(*IndicesShrinkRequest)) (*Response, error) { - var r = IndicesShrinkRequest{Index: index, Target: target} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesShrink allow to shrink an existing index into a new index with fewer primary shards. -// -// -type IndicesShrink func(index string, target string, o ...func(*IndicesShrinkRequest)) (*Response, error) - -// IndicesShrinkRequest configures the Indices Shrink API request. -// -type IndicesShrinkRequest struct { - Index string - - Body io.Reader - - Target string - - CopySettings *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesShrinkRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len(r.Index) + 1 + len("_shrink") + 1 + len(r.Target)) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_shrink") - path.WriteString("/") - path.WriteString(r.Target) - - params = make(map[string]string) - - if r.CopySettings != nil { - params["copy_settings"] = strconv.FormatBool(*r.CopySettings) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesShrink) WithContext(v context.Context) func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.ctx = v - } -} - -// WithBody - The configuration for the target index (`settings` and `aliases`). -// -func (f IndicesShrink) WithBody(v io.Reader) func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.Body = v - } -} - -// WithCopySettings - whether or not to copy settings from the source index (defaults to false). -// -func (f IndicesShrink) WithCopySettings(v bool) func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.CopySettings = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesShrink) WithMasterTimeout(v time.Duration) func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesShrink) WithClusterManagerTimeout(v time.Duration) func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesShrink) WithTimeout(v time.Duration) func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - set the number of active shards to wait for on the shrunken index before the operation returns.. -// -func (f IndicesShrink) WithWaitForActiveShards(v string) func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesShrink) WithPretty() func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesShrink) WithHuman() func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesShrink) WithErrorTrace() func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesShrink) WithFilterPath(v ...string) func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesShrink) WithHeader(h map[string]string) func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesShrink) WithOpaqueID(s string) func(*IndicesShrinkRequest) { - return func(r *IndicesShrinkRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.simulate_index_template.go b/opensearchapi/api.indices.simulate_index_template.go deleted file mode 100644 index 2912ffd71..000000000 --- a/opensearchapi/api.indices.simulate_index_template.go +++ /dev/null @@ -1,281 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesSimulateIndexTemplateFunc(t Transport) IndicesSimulateIndexTemplate { - return func(name string, o ...func(*IndicesSimulateIndexTemplateRequest)) (*Response, error) { - var r = IndicesSimulateIndexTemplateRequest{Name: name} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesSimulateIndexTemplate simulate matching the given index name against the index templates in the system -// -// -type IndicesSimulateIndexTemplate func(name string, o ...func(*IndicesSimulateIndexTemplateRequest)) (*Response, error) - -// IndicesSimulateIndexTemplateRequest configures the Indices Simulate Index Template API request. -// -type IndicesSimulateIndexTemplateRequest struct { - Body io.Reader - - Name string - - Cause string - Create *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesSimulateIndexTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_index_template") + 1 + len("_simulate_index") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_index_template") - path.WriteString("/") - path.WriteString("_simulate_index") - path.WriteString("/") - path.WriteString(r.Name) - - params = make(map[string]string) - - if r.Cause != "" { - params["cause"] = r.Cause - } - - if r.Create != nil { - params["create"] = strconv.FormatBool(*r.Create) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesSimulateIndexTemplate) WithContext(v context.Context) func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - r.ctx = v - } -} - -// WithBody - New index template definition, which will be included in the simulation, as if it already exists in the system. -// -func (f IndicesSimulateIndexTemplate) WithBody(v io.Reader) func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - r.Body = v - } -} - -// WithCause - user defined reason for dry-run creating the new template for simulation purposes. -// -func (f IndicesSimulateIndexTemplate) WithCause(v string) func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - r.Cause = v - } -} - -// WithCreate - whether the index template we optionally defined in the body should only be dry-run added if new or can also replace an existing one. -// -func (f IndicesSimulateIndexTemplate) WithCreate(v bool) func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - r.Create = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesSimulateIndexTemplate) WithMasterTimeout(v time.Duration) func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesSimulateIndexTemplate) WithClusterManagerTimeout(v time.Duration) func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesSimulateIndexTemplate) WithPretty() func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesSimulateIndexTemplate) WithHuman() func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesSimulateIndexTemplate) WithErrorTrace() func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesSimulateIndexTemplate) WithFilterPath(v ...string) func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesSimulateIndexTemplate) WithHeader(h map[string]string) func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesSimulateIndexTemplate) WithOpaqueID(s string) func(*IndicesSimulateIndexTemplateRequest) { - return func(r *IndicesSimulateIndexTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.simulate_template.go b/opensearchapi/api.indices.simulate_template.go deleted file mode 100644 index aeb573861..000000000 --- a/opensearchapi/api.indices.simulate_template.go +++ /dev/null @@ -1,291 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesSimulateTemplateFunc(t Transport) IndicesSimulateTemplate { - return func(o ...func(*IndicesSimulateTemplateRequest)) (*Response, error) { - var r = IndicesSimulateTemplateRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesSimulateTemplate simulate resolving the given template name or body -// -// -type IndicesSimulateTemplate func(o ...func(*IndicesSimulateTemplateRequest)) (*Response, error) - -// IndicesSimulateTemplateRequest configures the Indices Simulate Template API request. -// -type IndicesSimulateTemplateRequest struct { - Body io.Reader - - Name string - - Cause string - Create *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesSimulateTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_index_template") + 1 + len("_simulate") + 1 + len(r.Name)) - path.WriteString("/") - path.WriteString("_index_template") - path.WriteString("/") - path.WriteString("_simulate") - if r.Name != "" { - path.WriteString("/") - path.WriteString(r.Name) - } - - params = make(map[string]string) - - if r.Cause != "" { - params["cause"] = r.Cause - } - - if r.Create != nil { - params["create"] = strconv.FormatBool(*r.Create) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesSimulateTemplate) WithContext(v context.Context) func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.ctx = v - } -} - -// WithBody - New index template definition to be simulated, if no index template name is specified. -// -func (f IndicesSimulateTemplate) WithBody(v io.Reader) func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.Body = v - } -} - -// WithName - the name of the index template. -// -func (f IndicesSimulateTemplate) WithName(v string) func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.Name = v - } -} - -// WithCause - user defined reason for dry-run creating the new template for simulation purposes. -// -func (f IndicesSimulateTemplate) WithCause(v string) func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.Cause = v - } -} - -// WithCreate - whether the index template we optionally defined in the body should only be dry-run added if new or can also replace an existing one. -// -func (f IndicesSimulateTemplate) WithCreate(v bool) func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.Create = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesSimulateTemplate) WithMasterTimeout(v time.Duration) func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesSimulateTemplate) WithClusterManagerTimeout(v time.Duration) func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesSimulateTemplate) WithPretty() func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesSimulateTemplate) WithHuman() func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesSimulateTemplate) WithErrorTrace() func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesSimulateTemplate) WithFilterPath(v ...string) func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesSimulateTemplate) WithHeader(h map[string]string) func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesSimulateTemplate) WithOpaqueID(s string) func(*IndicesSimulateTemplateRequest) { - return func(r *IndicesSimulateTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.split.go b/opensearchapi/api.indices.split.go deleted file mode 100644 index 49ea6c5e5..000000000 --- a/opensearchapi/api.indices.split.go +++ /dev/null @@ -1,296 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newIndicesSplitFunc(t Transport) IndicesSplit { - return func(index string, target string, o ...func(*IndicesSplitRequest)) (*Response, error) { - var r = IndicesSplitRequest{Index: index, Target: target} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesSplit allows you to split an existing index into a new index with more primary shards. -// -// -type IndicesSplit func(index string, target string, o ...func(*IndicesSplitRequest)) (*Response, error) - -// IndicesSplitRequest configures the Indices Split API request. -// -type IndicesSplitRequest struct { - Index string - - Body io.Reader - - Target string - - CopySettings *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesSplitRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len(r.Index) + 1 + len("_split") + 1 + len(r.Target)) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_split") - path.WriteString("/") - path.WriteString(r.Target) - - params = make(map[string]string) - - if r.CopySettings != nil { - params["copy_settings"] = strconv.FormatBool(*r.CopySettings) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesSplit) WithContext(v context.Context) func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.ctx = v - } -} - -// WithBody - The configuration for the target index (`settings` and `aliases`). -// -func (f IndicesSplit) WithBody(v io.Reader) func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.Body = v - } -} - -// WithCopySettings - whether or not to copy settings from the source index (defaults to false). -// -func (f IndicesSplit) WithCopySettings(v bool) func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.CopySettings = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesSplit) WithMasterTimeout(v time.Duration) func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesSplit) WithClusterManagerTimeout(v time.Duration) func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IndicesSplit) WithTimeout(v time.Duration) func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - set the number of active shards to wait for on the shrunken index before the operation returns.. -// -func (f IndicesSplit) WithWaitForActiveShards(v string) func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesSplit) WithPretty() func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesSplit) WithHuman() func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesSplit) WithErrorTrace() func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesSplit) WithFilterPath(v ...string) func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesSplit) WithHeader(h map[string]string) func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesSplit) WithOpaqueID(s string) func(*IndicesSplitRequest) { - return func(r *IndicesSplitRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.stats.go b/opensearchapi/api.indices.stats.go deleted file mode 100644 index 27b55d592..000000000 --- a/opensearchapi/api.indices.stats.go +++ /dev/null @@ -1,363 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesStatsFunc(t Transport) IndicesStats { - return func(o ...func(*IndicesStatsRequest)) (*Response, error) { - var r = IndicesStatsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesStats provides statistics on operations happening in an index. -// -// -type IndicesStats func(o ...func(*IndicesStatsRequest)) (*Response, error) - -// IndicesStatsRequest configures the Indices Stats API request. -// -type IndicesStatsRequest struct { - Index []string - - Metric []string - - CompletionFields []string - ExpandWildcards string - FielddataFields []string - Fields []string - ForbidClosedIndices *bool - Groups []string - IncludeSegmentFileSizes *bool - IncludeUnloadedSegments *bool - Level string - Types []string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesStatsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_stats") + 1 + len(strings.Join(r.Metric, ","))) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_stats") - if len(r.Metric) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Metric, ",")) - } - - params = make(map[string]string) - - if len(r.CompletionFields) > 0 { - params["completion_fields"] = strings.Join(r.CompletionFields, ",") - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if len(r.FielddataFields) > 0 { - params["fielddata_fields"] = strings.Join(r.FielddataFields, ",") - } - - if len(r.Fields) > 0 { - params["fields"] = strings.Join(r.Fields, ",") - } - - if r.ForbidClosedIndices != nil { - params["forbid_closed_indices"] = strconv.FormatBool(*r.ForbidClosedIndices) - } - - if len(r.Groups) > 0 { - params["groups"] = strings.Join(r.Groups, ",") - } - - if r.IncludeSegmentFileSizes != nil { - params["include_segment_file_sizes"] = strconv.FormatBool(*r.IncludeSegmentFileSizes) - } - - if r.IncludeUnloadedSegments != nil { - params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments) - } - - if r.Level != "" { - params["level"] = r.Level - } - - if len(r.Types) > 0 { - params["types"] = strings.Join(r.Types, ",") - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesStats) WithContext(v context.Context) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f IndicesStats) WithIndex(v ...string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.Index = v - } -} - -// WithMetric - limit the information returned the specific metrics.. -// -func (f IndicesStats) WithMetric(v ...string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.Metric = v - } -} - -// WithCompletionFields - a list of fields for `fielddata` and `suggest` index metric (supports wildcards). -// -func (f IndicesStats) WithCompletionFields(v ...string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.CompletionFields = v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesStats) WithExpandWildcards(v string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.ExpandWildcards = v - } -} - -// WithFielddataFields - a list of fields for `fielddata` index metric (supports wildcards). -// -func (f IndicesStats) WithFielddataFields(v ...string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.FielddataFields = v - } -} - -// WithFields - a list of fields for `fielddata` and `completion` index metric (supports wildcards). -// -func (f IndicesStats) WithFields(v ...string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.Fields = v - } -} - -// WithForbidClosedIndices - if set to false stats will also collected from closed indices if explicitly specified or if expand_wildcards expands to closed indices. -// -func (f IndicesStats) WithForbidClosedIndices(v bool) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.ForbidClosedIndices = &v - } -} - -// WithGroups - a list of search groups for `search` index metric. -// -func (f IndicesStats) WithGroups(v ...string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.Groups = v - } -} - -// WithIncludeSegmentFileSizes - whether to report the aggregated disk usage of each one of the lucene index files (only applies if segment stats are requested). -// -func (f IndicesStats) WithIncludeSegmentFileSizes(v bool) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.IncludeSegmentFileSizes = &v - } -} - -// WithIncludeUnloadedSegments - if set to true segment stats will include stats for segments that are not currently loaded into memory. -// -func (f IndicesStats) WithIncludeUnloadedSegments(v bool) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.IncludeUnloadedSegments = &v - } -} - -// WithLevel - return stats aggregated at cluster, index or shard level. -// -func (f IndicesStats) WithLevel(v string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.Level = v - } -} - -// WithTypes - a list of document types for the `indexing` index metric. -// -func (f IndicesStats) WithTypes(v ...string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.Types = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesStats) WithPretty() func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesStats) WithHuman() func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesStats) WithErrorTrace() func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesStats) WithFilterPath(v ...string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesStats) WithHeader(h map[string]string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesStats) WithOpaqueID(s string) func(*IndicesStatsRequest) { - return func(r *IndicesStatsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.update_aliases.go b/opensearchapi/api.indices.update_aliases.go deleted file mode 100644 index 9f3bb772a..000000000 --- a/opensearchapi/api.indices.update_aliases.go +++ /dev/null @@ -1,252 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" - "time" -) - -func newIndicesUpdateAliasesFunc(t Transport) IndicesUpdateAliases { - return func(body io.Reader, o ...func(*IndicesUpdateAliasesRequest)) (*Response, error) { - var r = IndicesUpdateAliasesRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesUpdateAliases updates index aliases. -// -// -type IndicesUpdateAliases func(body io.Reader, o ...func(*IndicesUpdateAliasesRequest)) (*Response, error) - -// IndicesUpdateAliasesRequest configures the Indices Update Aliases API request. -// -type IndicesUpdateAliasesRequest struct { - Body io.Reader - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesUpdateAliasesRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(len("/_aliases")) - path.WriteString("/_aliases") - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesUpdateAliases) WithContext(v context.Context) func(*IndicesUpdateAliasesRequest) { - return func(r *IndicesUpdateAliasesRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IndicesUpdateAliases) WithMasterTimeout(v time.Duration) func(*IndicesUpdateAliasesRequest) { - return func(r *IndicesUpdateAliasesRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IndicesUpdateAliases) WithClusterManagerTimeout(v time.Duration) func(*IndicesUpdateAliasesRequest) { - return func(r *IndicesUpdateAliasesRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - request timeout. -// -func (f IndicesUpdateAliases) WithTimeout(v time.Duration) func(*IndicesUpdateAliasesRequest) { - return func(r *IndicesUpdateAliasesRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesUpdateAliases) WithPretty() func(*IndicesUpdateAliasesRequest) { - return func(r *IndicesUpdateAliasesRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesUpdateAliases) WithHuman() func(*IndicesUpdateAliasesRequest) { - return func(r *IndicesUpdateAliasesRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesUpdateAliases) WithErrorTrace() func(*IndicesUpdateAliasesRequest) { - return func(r *IndicesUpdateAliasesRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesUpdateAliases) WithFilterPath(v ...string) func(*IndicesUpdateAliasesRequest) { - return func(r *IndicesUpdateAliasesRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesUpdateAliases) WithHeader(h map[string]string) func(*IndicesUpdateAliasesRequest) { - return func(r *IndicesUpdateAliasesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesUpdateAliases) WithOpaqueID(s string) func(*IndicesUpdateAliasesRequest) { - return func(r *IndicesUpdateAliasesRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.upgrade.go b/opensearchapi/api.indices.upgrade.go deleted file mode 100644 index e505b6f88..000000000 --- a/opensearchapi/api.indices.upgrade.go +++ /dev/null @@ -1,284 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newIndicesUpgradeFunc(t Transport) IndicesUpgrade { - return func(o ...func(*IndicesUpgradeRequest)) (*Response, error) { - var r = IndicesUpgradeRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesUpgrade deprecated Upgrades to the current version of Lucene. -// -// -type IndicesUpgrade func(o ...func(*IndicesUpgradeRequest)) (*Response, error) - -// IndicesUpgradeRequest configures the Indices Upgrade API request. -// -type IndicesUpgradeRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - OnlyAncientSegments *bool - WaitForCompletion *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesUpgradeRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_upgrade")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_upgrade") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.OnlyAncientSegments != nil { - params["only_ancient_segments"] = strconv.FormatBool(*r.OnlyAncientSegments) - } - - if r.WaitForCompletion != nil { - params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesUpgrade) WithContext(v context.Context) func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names; use _all to perform the operation on all indices. -// -func (f IndicesUpgrade) WithIndex(v ...string) func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesUpgrade) WithAllowNoIndices(v bool) func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesUpgrade) WithExpandWildcards(v string) func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesUpgrade) WithIgnoreUnavailable(v bool) func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithOnlyAncientSegments - if true, only ancient (an older lucene major release) segments will be upgraded. -// -func (f IndicesUpgrade) WithOnlyAncientSegments(v bool) func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.OnlyAncientSegments = &v - } -} - -// WithWaitForCompletion - specify whether the request should block until the all segments are upgraded (default: false). -// -func (f IndicesUpgrade) WithWaitForCompletion(v bool) func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.WaitForCompletion = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesUpgrade) WithPretty() func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesUpgrade) WithHuman() func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesUpgrade) WithErrorTrace() func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesUpgrade) WithFilterPath(v ...string) func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesUpgrade) WithHeader(h map[string]string) func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesUpgrade) WithOpaqueID(s string) func(*IndicesUpgradeRequest) { - return func(r *IndicesUpgradeRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.indices.validate_query.go b/opensearchapi/api.indices.validate_query.go deleted file mode 100644 index db19a59ec..000000000 --- a/opensearchapi/api.indices.validate_query.go +++ /dev/null @@ -1,392 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newIndicesValidateQueryFunc(t Transport) IndicesValidateQuery { - return func(o ...func(*IndicesValidateQueryRequest)) (*Response, error) { - var r = IndicesValidateQueryRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IndicesValidateQuery allows a user to validate a potentially expensive query without executing it. -// -// -type IndicesValidateQuery func(o ...func(*IndicesValidateQueryRequest)) (*Response, error) - -// IndicesValidateQueryRequest configures the Indices Validate Query API request. -// -type IndicesValidateQueryRequest struct { - Index []string - - Body io.Reader - - AllowNoIndices *bool - AllShards *bool - Analyzer string - AnalyzeWildcard *bool - DefaultOperator string - Df string - ExpandWildcards string - Explain *bool - IgnoreUnavailable *bool - Lenient *bool - Query string - Rewrite *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IndicesValidateQueryRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_validate") + 1 + len("query")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_validate") - path.WriteString("/") - path.WriteString("query") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.AllShards != nil { - params["all_shards"] = strconv.FormatBool(*r.AllShards) - } - - if r.Analyzer != "" { - params["analyzer"] = r.Analyzer - } - - if r.AnalyzeWildcard != nil { - params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) - } - - if r.DefaultOperator != "" { - params["default_operator"] = r.DefaultOperator - } - - if r.Df != "" { - params["df"] = r.Df - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Explain != nil { - params["explain"] = strconv.FormatBool(*r.Explain) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Lenient != nil { - params["lenient"] = strconv.FormatBool(*r.Lenient) - } - - if r.Query != "" { - params["q"] = r.Query - } - - if r.Rewrite != nil { - params["rewrite"] = strconv.FormatBool(*r.Rewrite) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IndicesValidateQuery) WithContext(v context.Context) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.ctx = v - } -} - -// WithBody - The query definition specified with the Query DSL. -// -func (f IndicesValidateQuery) WithBody(v io.Reader) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.Body = v - } -} - -// WithIndex - a list of index names to restrict the operation; use _all to perform the operation on all indices. -// -func (f IndicesValidateQuery) WithIndex(v ...string) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f IndicesValidateQuery) WithAllowNoIndices(v bool) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.AllowNoIndices = &v - } -} - -// WithAllShards - execute validation on all shards instead of one random shard per index. -// -func (f IndicesValidateQuery) WithAllShards(v bool) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.AllShards = &v - } -} - -// WithAnalyzer - the analyzer to use for the query string. -// -func (f IndicesValidateQuery) WithAnalyzer(v string) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.Analyzer = v - } -} - -// WithAnalyzeWildcard - specify whether wildcard and prefix queries should be analyzed (default: false). -// -func (f IndicesValidateQuery) WithAnalyzeWildcard(v bool) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.AnalyzeWildcard = &v - } -} - -// WithDefaultOperator - the default operator for query string query (and or or). -// -func (f IndicesValidateQuery) WithDefaultOperator(v string) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.DefaultOperator = v - } -} - -// WithDf - the field to use as default where no field prefix is given in the query string. -// -func (f IndicesValidateQuery) WithDf(v string) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.Df = v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f IndicesValidateQuery) WithExpandWildcards(v string) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.ExpandWildcards = v - } -} - -// WithExplain - return detailed information about the error. -// -func (f IndicesValidateQuery) WithExplain(v bool) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.Explain = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f IndicesValidateQuery) WithIgnoreUnavailable(v bool) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithLenient - specify whether format-based query failures (such as providing text to a numeric field) should be ignored. -// -func (f IndicesValidateQuery) WithLenient(v bool) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.Lenient = &v - } -} - -// WithQuery - query in the lucene query string syntax. -// -func (f IndicesValidateQuery) WithQuery(v string) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.Query = v - } -} - -// WithRewrite - provide a more detailed explanation showing the actual lucene query that will be executed.. -// -func (f IndicesValidateQuery) WithRewrite(v bool) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.Rewrite = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IndicesValidateQuery) WithPretty() func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IndicesValidateQuery) WithHuman() func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IndicesValidateQuery) WithErrorTrace() func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IndicesValidateQuery) WithFilterPath(v ...string) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IndicesValidateQuery) WithHeader(h map[string]string) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IndicesValidateQuery) WithOpaqueID(s string) func(*IndicesValidateQueryRequest) { - return func(r *IndicesValidateQueryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.info.go b/opensearchapi/api.info.go deleted file mode 100644 index 995c5e982..000000000 --- a/opensearchapi/api.info.go +++ /dev/null @@ -1,203 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" -) - -func newInfoFunc(t Transport) Info { - return func(o ...func(*InfoRequest)) (*Response, error) { - var r = InfoRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Info returns basic information about the cluster. -type Info func(o ...func(*InfoRequest)) (*Response, error) - -// InfoRequest configures the Info API request. -type InfoRequest struct { - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// InfoResp is a custom type to parse the Info Reponse -type InfoResp struct { - Name string `json:"name"` - ClusterName string `json:"cluster_name"` - ClusterUUID string `json:"cluster_uuid"` - Version struct { - Distribution string `json:"distribution"` - Number string `json:"number"` - BuildType string `json:"build_type"` - BuildHash string `json:"build_hash"` - BuildDate string `json:"build_date"` - BuildSnapshot bool `json:"build_snapshot"` - LuceneVersion string `json:"lucene_version"` - MinimumWireCompatibilityVersion string `json:"minimum_wire_compatibility_version"` - MinimumIndexCompatibilityVersion string `json:"minimum_index_compatibility_version"` - } `json:"version"` - Tagline string `json:"tagline"` -} - -// Do executes the request and returns response or error. -func (r InfoRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/")) - path.WriteString("/") - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -func (f Info) WithContext(v context.Context) func(*InfoRequest) { - return func(r *InfoRequest) { - r.ctx = v - } -} - -// WithHuman makes statistical values human-readable. -func (f Info) WithHuman() func(*InfoRequest) { - return func(r *InfoRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -func (f Info) WithErrorTrace() func(*InfoRequest) { - return func(r *InfoRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -func (f Info) WithFilterPath(v ...string) func(*InfoRequest) { - return func(r *InfoRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -func (f Info) WithHeader(h map[string]string) func(*InfoRequest) { - return func(r *InfoRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -func (f Info) WithOpaqueID(s string) func(*InfoRequest) { - return func(r *InfoRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.ingest.delete_pipeline.go b/opensearchapi/api.ingest.delete_pipeline.go deleted file mode 100644 index 1e8dd1eee..000000000 --- a/opensearchapi/api.ingest.delete_pipeline.go +++ /dev/null @@ -1,252 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newIngestDeletePipelineFunc(t Transport) IngestDeletePipeline { - return func(id string, o ...func(*IngestDeletePipelineRequest)) (*Response, error) { - var r = IngestDeletePipelineRequest{PipelineID: id} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IngestDeletePipeline deletes a pipeline. -// -// -type IngestDeletePipeline func(id string, o ...func(*IngestDeletePipelineRequest)) (*Response, error) - -// IngestDeletePipelineRequest configures the Ingest Delete Pipeline API request. -// -type IngestDeletePipelineRequest struct { - PipelineID string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IngestDeletePipelineRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len("_ingest") + 1 + len("pipeline") + 1 + len(r.PipelineID)) - path.WriteString("/") - path.WriteString("_ingest") - path.WriteString("/") - path.WriteString("pipeline") - path.WriteString("/") - path.WriteString(r.PipelineID) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IngestDeletePipeline) WithContext(v context.Context) func(*IngestDeletePipelineRequest) { - return func(r *IngestDeletePipelineRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IngestDeletePipeline) WithMasterTimeout(v time.Duration) func(*IngestDeletePipelineRequest) { - return func(r *IngestDeletePipelineRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IngestDeletePipeline) WithClusterManagerTimeout(v time.Duration) func(*IngestDeletePipelineRequest) { - return func(r *IngestDeletePipelineRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IngestDeletePipeline) WithTimeout(v time.Duration) func(*IngestDeletePipelineRequest) { - return func(r *IngestDeletePipelineRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IngestDeletePipeline) WithPretty() func(*IngestDeletePipelineRequest) { - return func(r *IngestDeletePipelineRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IngestDeletePipeline) WithHuman() func(*IngestDeletePipelineRequest) { - return func(r *IngestDeletePipelineRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IngestDeletePipeline) WithErrorTrace() func(*IngestDeletePipelineRequest) { - return func(r *IngestDeletePipelineRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IngestDeletePipeline) WithFilterPath(v ...string) func(*IngestDeletePipelineRequest) { - return func(r *IngestDeletePipelineRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IngestDeletePipeline) WithHeader(h map[string]string) func(*IngestDeletePipelineRequest) { - return func(r *IngestDeletePipelineRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IngestDeletePipeline) WithOpaqueID(s string) func(*IngestDeletePipelineRequest) { - return func(r *IngestDeletePipelineRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.ingest.get_pipeline.go b/opensearchapi/api.ingest.get_pipeline.go deleted file mode 100644 index bbfd41763..000000000 --- a/opensearchapi/api.ingest.get_pipeline.go +++ /dev/null @@ -1,263 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newIngestGetPipelineFunc(t Transport) IngestGetPipeline { - return func(o ...func(*IngestGetPipelineRequest)) (*Response, error) { - var r = IngestGetPipelineRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IngestGetPipeline returns a pipeline. -// -// -type IngestGetPipeline func(o ...func(*IngestGetPipelineRequest)) (*Response, error) - -// IngestGetPipelineRequest configures the Ingest Get Pipeline API request. -// -type IngestGetPipelineRequest struct { - PipelineID string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Summary *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IngestGetPipelineRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_ingest") + 1 + len("pipeline") + 1 + len(r.PipelineID)) - path.WriteString("/") - path.WriteString("_ingest") - path.WriteString("/") - path.WriteString("pipeline") - if r.PipelineID != "" { - path.WriteString("/") - path.WriteString(r.PipelineID) - } - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Summary != nil { - params["summary"] = strconv.FormatBool(*r.Summary) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IngestGetPipeline) WithContext(v context.Context) func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - r.ctx = v - } -} - -// WithPipelineID - comma separated list of pipeline ids. wildcards supported. -// -func (f IngestGetPipeline) WithPipelineID(v string) func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - r.PipelineID = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IngestGetPipeline) WithMasterTimeout(v time.Duration) func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IngestGetPipeline) WithClusterManagerTimeout(v time.Duration) func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithSummary - return pipelines without their definitions (default: false). -// -func (f IngestGetPipeline) WithSummary(v bool) func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - r.Summary = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IngestGetPipeline) WithPretty() func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IngestGetPipeline) WithHuman() func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IngestGetPipeline) WithErrorTrace() func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IngestGetPipeline) WithFilterPath(v ...string) func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IngestGetPipeline) WithHeader(h map[string]string) func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IngestGetPipeline) WithOpaqueID(s string) func(*IngestGetPipelineRequest) { - return func(r *IngestGetPipelineRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.ingest.processor_grok.go b/opensearchapi/api.ingest.processor_grok.go deleted file mode 100644 index af506ab41..000000000 --- a/opensearchapi/api.ingest.processor_grok.go +++ /dev/null @@ -1,202 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" -) - -func newIngestProcessorGrokFunc(t Transport) IngestProcessorGrok { - return func(o ...func(*IngestProcessorGrokRequest)) (*Response, error) { - var r = IngestProcessorGrokRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IngestProcessorGrok returns a list of the built-in patterns. -// -// -type IngestProcessorGrok func(o ...func(*IngestProcessorGrokRequest)) (*Response, error) - -// IngestProcessorGrokRequest configures the Ingest Processor Grok API request. -// -type IngestProcessorGrokRequest struct { - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IngestProcessorGrokRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_ingest/processor/grok")) - path.WriteString("/_ingest/processor/grok") - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IngestProcessorGrok) WithContext(v context.Context) func(*IngestProcessorGrokRequest) { - return func(r *IngestProcessorGrokRequest) { - r.ctx = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IngestProcessorGrok) WithPretty() func(*IngestProcessorGrokRequest) { - return func(r *IngestProcessorGrokRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IngestProcessorGrok) WithHuman() func(*IngestProcessorGrokRequest) { - return func(r *IngestProcessorGrokRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IngestProcessorGrok) WithErrorTrace() func(*IngestProcessorGrokRequest) { - return func(r *IngestProcessorGrokRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IngestProcessorGrok) WithFilterPath(v ...string) func(*IngestProcessorGrokRequest) { - return func(r *IngestProcessorGrokRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IngestProcessorGrok) WithHeader(h map[string]string) func(*IngestProcessorGrokRequest) { - return func(r *IngestProcessorGrokRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IngestProcessorGrok) WithOpaqueID(s string) func(*IngestProcessorGrokRequest) { - return func(r *IngestProcessorGrokRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.ingest.put_pipeline.go b/opensearchapi/api.ingest.put_pipeline.go deleted file mode 100644 index 5a0bea0b6..000000000 --- a/opensearchapi/api.ingest.put_pipeline.go +++ /dev/null @@ -1,259 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" - "time" -) - -func newIngestPutPipelineFunc(t Transport) IngestPutPipeline { - return func(id string, body io.Reader, o ...func(*IngestPutPipelineRequest)) (*Response, error) { - var r = IngestPutPipelineRequest{PipelineID: id, Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IngestPutPipeline creates or updates a pipeline. -// -// -type IngestPutPipeline func(id string, body io.Reader, o ...func(*IngestPutPipelineRequest)) (*Response, error) - -// IngestPutPipelineRequest configures the Ingest Put Pipeline API request. -// -type IngestPutPipelineRequest struct { - PipelineID string - - Body io.Reader - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IngestPutPipelineRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len("_ingest") + 1 + len("pipeline") + 1 + len(r.PipelineID)) - path.WriteString("/") - path.WriteString("_ingest") - path.WriteString("/") - path.WriteString("pipeline") - path.WriteString("/") - path.WriteString(r.PipelineID) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IngestPutPipeline) WithContext(v context.Context) func(*IngestPutPipelineRequest) { - return func(r *IngestPutPipelineRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f IngestPutPipeline) WithMasterTimeout(v time.Duration) func(*IngestPutPipelineRequest) { - return func(r *IngestPutPipelineRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f IngestPutPipeline) WithClusterManagerTimeout(v time.Duration) func(*IngestPutPipelineRequest) { - return func(r *IngestPutPipelineRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f IngestPutPipeline) WithTimeout(v time.Duration) func(*IngestPutPipelineRequest) { - return func(r *IngestPutPipelineRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IngestPutPipeline) WithPretty() func(*IngestPutPipelineRequest) { - return func(r *IngestPutPipelineRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IngestPutPipeline) WithHuman() func(*IngestPutPipelineRequest) { - return func(r *IngestPutPipelineRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IngestPutPipeline) WithErrorTrace() func(*IngestPutPipelineRequest) { - return func(r *IngestPutPipelineRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IngestPutPipeline) WithFilterPath(v ...string) func(*IngestPutPipelineRequest) { - return func(r *IngestPutPipelineRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IngestPutPipeline) WithHeader(h map[string]string) func(*IngestPutPipelineRequest) { - return func(r *IngestPutPipelineRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IngestPutPipeline) WithOpaqueID(s string) func(*IngestPutPipelineRequest) { - return func(r *IngestPutPipelineRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.ingest.simulate.go b/opensearchapi/api.ingest.simulate.go deleted file mode 100644 index 926d01994..000000000 --- a/opensearchapi/api.ingest.simulate.go +++ /dev/null @@ -1,243 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newIngestSimulateFunc(t Transport) IngestSimulate { - return func(body io.Reader, o ...func(*IngestSimulateRequest)) (*Response, error) { - var r = IngestSimulateRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// IngestSimulate allows to simulate a pipeline with example documents. -// -// -type IngestSimulate func(body io.Reader, o ...func(*IngestSimulateRequest)) (*Response, error) - -// IngestSimulateRequest configures the Ingest Simulate API request. -// -type IngestSimulateRequest struct { - PipelineID string - - Body io.Reader - - Verbose *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r IngestSimulateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_ingest") + 1 + len("pipeline") + 1 + len(r.PipelineID) + 1 + len("_simulate")) - path.WriteString("/") - path.WriteString("_ingest") - path.WriteString("/") - path.WriteString("pipeline") - if r.PipelineID != "" { - path.WriteString("/") - path.WriteString(r.PipelineID) - } - path.WriteString("/") - path.WriteString("_simulate") - - params = make(map[string]string) - - if r.Verbose != nil { - params["verbose"] = strconv.FormatBool(*r.Verbose) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f IngestSimulate) WithContext(v context.Context) func(*IngestSimulateRequest) { - return func(r *IngestSimulateRequest) { - r.ctx = v - } -} - -// WithPipelineID - pipeline ID. -// -func (f IngestSimulate) WithPipelineID(v string) func(*IngestSimulateRequest) { - return func(r *IngestSimulateRequest) { - r.PipelineID = v - } -} - -// WithVerbose - verbose mode. display data output for each processor in executed pipeline. -// -func (f IngestSimulate) WithVerbose(v bool) func(*IngestSimulateRequest) { - return func(r *IngestSimulateRequest) { - r.Verbose = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f IngestSimulate) WithPretty() func(*IngestSimulateRequest) { - return func(r *IngestSimulateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f IngestSimulate) WithHuman() func(*IngestSimulateRequest) { - return func(r *IngestSimulateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f IngestSimulate) WithErrorTrace() func(*IngestSimulateRequest) { - return func(r *IngestSimulateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f IngestSimulate) WithFilterPath(v ...string) func(*IngestSimulateRequest) { - return func(r *IngestSimulateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f IngestSimulate) WithHeader(h map[string]string) func(*IngestSimulateRequest) { - return func(r *IngestSimulateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f IngestSimulate) WithOpaqueID(s string) func(*IngestSimulateRequest) { - return func(r *IngestSimulateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.mget.go b/opensearchapi/api.mget.go deleted file mode 100644 index 546050f9e..000000000 --- a/opensearchapi/api.mget.go +++ /dev/null @@ -1,334 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newMgetFunc(t Transport) Mget { - return func(body io.Reader, o ...func(*MgetRequest)) (*Response, error) { - var r = MgetRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Mget allows to get multiple documents in one request. -// -// -type Mget func(body io.Reader, o ...func(*MgetRequest)) (*Response, error) - -// MgetRequest configures the Mget API request. -// -type MgetRequest struct { - Index string - - Body io.Reader - - Preference string - Realtime *bool - Refresh *bool - Routing string - Source interface{} - SourceExcludes []string - SourceIncludes []string - StoredFields []string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r MgetRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(r.Index) + 1 + len("_mget")) - if r.Index != "" { - path.WriteString("/") - path.WriteString(r.Index) - } - path.WriteString("/") - path.WriteString("_mget") - - params = make(map[string]string) - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Realtime != nil { - params["realtime"] = strconv.FormatBool(*r.Realtime) - } - - if r.Refresh != nil { - params["refresh"] = strconv.FormatBool(*r.Refresh) - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if source, ok := r.Source.(bool); ok { - params["_source"] = strconv.FormatBool(source) - } else if source, ok := r.Source.(string); ok && source != "" { - params["_source"] = source - } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { - params["_source"] = strings.Join(sources, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if len(r.StoredFields) > 0 { - params["stored_fields"] = strings.Join(r.StoredFields, ",") - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Mget) WithContext(v context.Context) func(*MgetRequest) { - return func(r *MgetRequest) { - r.ctx = v - } -} - -// WithIndex - the name of the index. -// -func (f Mget) WithIndex(v string) func(*MgetRequest) { - return func(r *MgetRequest) { - r.Index = v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f Mget) WithPreference(v string) func(*MgetRequest) { - return func(r *MgetRequest) { - r.Preference = v - } -} - -// WithRealtime - specify whether to perform the operation in realtime or search mode. -// -func (f Mget) WithRealtime(v bool) func(*MgetRequest) { - return func(r *MgetRequest) { - r.Realtime = &v - } -} - -// WithRefresh - refresh the shard containing the document before performing the operation. -// -func (f Mget) WithRefresh(v bool) func(*MgetRequest) { - return func(r *MgetRequest) { - r.Refresh = &v - } -} - -// WithRouting - specific routing value. -// -func (f Mget) WithRouting(v string) func(*MgetRequest) { - return func(r *MgetRequest) { - r.Routing = v - } -} - -// WithSource - true or false to return the _source field or not, or a list of fields to return. -// -func (f Mget) WithSource(v interface{}) func(*MgetRequest) { - return func(r *MgetRequest) { - r.Source = v - } -} - -// WithSourceExcludes - a list of fields to exclude from the returned _source field. -// -func (f Mget) WithSourceExcludes(v ...string) func(*MgetRequest) { - return func(r *MgetRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - a list of fields to extract and return from the _source field. -// -func (f Mget) WithSourceIncludes(v ...string) func(*MgetRequest) { - return func(r *MgetRequest) { - r.SourceIncludes = v - } -} - -// WithStoredFields - a list of stored fields to return in the response. -// -func (f Mget) WithStoredFields(v ...string) func(*MgetRequest) { - return func(r *MgetRequest) { - r.StoredFields = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Mget) WithPretty() func(*MgetRequest) { - return func(r *MgetRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Mget) WithHuman() func(*MgetRequest) { - return func(r *MgetRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Mget) WithErrorTrace() func(*MgetRequest) { - return func(r *MgetRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Mget) WithFilterPath(v ...string) func(*MgetRequest) { - return func(r *MgetRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Mget) WithHeader(h map[string]string) func(*MgetRequest) { - return func(r *MgetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Mget) WithOpaqueID(s string) func(*MgetRequest) { - return func(r *MgetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.msearch.go b/opensearchapi/api.msearch.go deleted file mode 100644 index edbf7e308..000000000 --- a/opensearchapi/api.msearch.go +++ /dev/null @@ -1,317 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newMsearchFunc(t Transport) Msearch { - return func(body io.Reader, o ...func(*MsearchRequest)) (*Response, error) { - var r = MsearchRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Msearch allows to execute several search operations in one request. -// -// -type Msearch func(body io.Reader, o ...func(*MsearchRequest)) (*Response, error) - -// MsearchRequest configures the Msearch API request. -// -type MsearchRequest struct { - Index []string - - Body io.Reader - - CcsMinimizeRoundtrips *bool - MaxConcurrentSearches *int - MaxConcurrentShardRequests *int - PreFilterShardSize *int - RestTotalHitsAsInt *bool - SearchType string - TypedKeys *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r MsearchRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_msearch")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_msearch") - - params = make(map[string]string) - - if r.CcsMinimizeRoundtrips != nil { - params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) - } - - if r.MaxConcurrentSearches != nil { - params["max_concurrent_searches"] = strconv.FormatInt(int64(*r.MaxConcurrentSearches), 10) - } - - if r.MaxConcurrentShardRequests != nil { - params["max_concurrent_shard_requests"] = strconv.FormatInt(int64(*r.MaxConcurrentShardRequests), 10) - } - - if r.PreFilterShardSize != nil { - params["pre_filter_shard_size"] = strconv.FormatInt(int64(*r.PreFilterShardSize), 10) - } - - if r.RestTotalHitsAsInt != nil { - params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) - } - - if r.SearchType != "" { - params["search_type"] = r.SearchType - } - - if r.TypedKeys != nil { - params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Msearch) WithContext(v context.Context) func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to use as default. -// -func (f Msearch) WithIndex(v ...string) func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.Index = v - } -} - -// WithCcsMinimizeRoundtrips - indicates whether network round-trips should be minimized as part of cross-cluster search requests execution. -// -func (f Msearch) WithCcsMinimizeRoundtrips(v bool) func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.CcsMinimizeRoundtrips = &v - } -} - -// WithMaxConcurrentSearches - controls the maximum number of concurrent searches the multi search api will execute. -// -func (f Msearch) WithMaxConcurrentSearches(v int) func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.MaxConcurrentSearches = &v - } -} - -// WithMaxConcurrentShardRequests - the number of concurrent shard requests each sub search executes concurrently per node. this value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests. -// -func (f Msearch) WithMaxConcurrentShardRequests(v int) func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.MaxConcurrentShardRequests = &v - } -} - -// WithPreFilterShardSize - a threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. this filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on its rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint.. -// -func (f Msearch) WithPreFilterShardSize(v int) func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.PreFilterShardSize = &v - } -} - -// WithRestTotalHitsAsInt - indicates whether hits.total should be rendered as an integer or an object in the rest search response. -// -func (f Msearch) WithRestTotalHitsAsInt(v bool) func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.RestTotalHitsAsInt = &v - } -} - -// WithSearchType - search operation type. -// -func (f Msearch) WithSearchType(v string) func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.SearchType = v - } -} - -// WithTypedKeys - specify whether aggregation and suggester names should be prefixed by their respective types in the response. -// -func (f Msearch) WithTypedKeys(v bool) func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.TypedKeys = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Msearch) WithPretty() func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Msearch) WithHuman() func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Msearch) WithErrorTrace() func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Msearch) WithFilterPath(v ...string) func(*MsearchRequest) { - return func(r *MsearchRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Msearch) WithHeader(h map[string]string) func(*MsearchRequest) { - return func(r *MsearchRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Msearch) WithOpaqueID(s string) func(*MsearchRequest) { - return func(r *MsearchRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.msearch_template.go b/opensearchapi/api.msearch_template.go deleted file mode 100644 index ea73c4eed..000000000 --- a/opensearchapi/api.msearch_template.go +++ /dev/null @@ -1,293 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newMsearchTemplateFunc(t Transport) MsearchTemplate { - return func(body io.Reader, o ...func(*MsearchTemplateRequest)) (*Response, error) { - var r = MsearchTemplateRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// MsearchTemplate allows to execute several search template operations in one request. -// -// -type MsearchTemplate func(body io.Reader, o ...func(*MsearchTemplateRequest)) (*Response, error) - -// MsearchTemplateRequest configures the Msearch Template API request. -// -type MsearchTemplateRequest struct { - Index []string - - Body io.Reader - - CcsMinimizeRoundtrips *bool - MaxConcurrentSearches *int - RestTotalHitsAsInt *bool - SearchType string - TypedKeys *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r MsearchTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_msearch") + 1 + len("template")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_msearch") - path.WriteString("/") - path.WriteString("template") - - params = make(map[string]string) - - if r.CcsMinimizeRoundtrips != nil { - params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) - } - - if r.MaxConcurrentSearches != nil { - params["max_concurrent_searches"] = strconv.FormatInt(int64(*r.MaxConcurrentSearches), 10) - } - - if r.RestTotalHitsAsInt != nil { - params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) - } - - if r.SearchType != "" { - params["search_type"] = r.SearchType - } - - if r.TypedKeys != nil { - params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f MsearchTemplate) WithContext(v context.Context) func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to use as default. -// -func (f MsearchTemplate) WithIndex(v ...string) func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.Index = v - } -} - -// WithCcsMinimizeRoundtrips - indicates whether network round-trips should be minimized as part of cross-cluster search requests execution. -// -func (f MsearchTemplate) WithCcsMinimizeRoundtrips(v bool) func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.CcsMinimizeRoundtrips = &v - } -} - -// WithMaxConcurrentSearches - controls the maximum number of concurrent searches the multi search api will execute. -// -func (f MsearchTemplate) WithMaxConcurrentSearches(v int) func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.MaxConcurrentSearches = &v - } -} - -// WithRestTotalHitsAsInt - indicates whether hits.total should be rendered as an integer or an object in the rest search response. -// -func (f MsearchTemplate) WithRestTotalHitsAsInt(v bool) func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.RestTotalHitsAsInt = &v - } -} - -// WithSearchType - search operation type. -// -func (f MsearchTemplate) WithSearchType(v string) func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.SearchType = v - } -} - -// WithTypedKeys - specify whether aggregation and suggester names should be prefixed by their respective types in the response. -// -func (f MsearchTemplate) WithTypedKeys(v bool) func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.TypedKeys = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f MsearchTemplate) WithPretty() func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f MsearchTemplate) WithHuman() func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f MsearchTemplate) WithErrorTrace() func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f MsearchTemplate) WithFilterPath(v ...string) func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f MsearchTemplate) WithHeader(h map[string]string) func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f MsearchTemplate) WithOpaqueID(s string) func(*MsearchTemplateRequest) { - return func(r *MsearchTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.mtermvectors.go b/opensearchapi/api.mtermvectors.go deleted file mode 100644 index 181d01f59..000000000 --- a/opensearchapi/api.mtermvectors.go +++ /dev/null @@ -1,390 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newMtermvectorsFunc(t Transport) Mtermvectors { - return func(o ...func(*MtermvectorsRequest)) (*Response, error) { - var r = MtermvectorsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Mtermvectors returns multiple termvectors in one request. -// -// -type Mtermvectors func(o ...func(*MtermvectorsRequest)) (*Response, error) - -// MtermvectorsRequest configures the Mtermvectors API request. -// -type MtermvectorsRequest struct { - Index string - - Body io.Reader - - Fields []string - FieldStatistics *bool - Ids []string - Offsets *bool - Payloads *bool - Positions *bool - Preference string - Realtime *bool - Routing string - TermStatistics *bool - Version *int - VersionType string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r MtermvectorsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(r.Index) + 1 + len("_mtermvectors")) - if r.Index != "" { - path.WriteString("/") - path.WriteString(r.Index) - } - path.WriteString("/") - path.WriteString("_mtermvectors") - - params = make(map[string]string) - - if len(r.Fields) > 0 { - params["fields"] = strings.Join(r.Fields, ",") - } - - if r.FieldStatistics != nil { - params["field_statistics"] = strconv.FormatBool(*r.FieldStatistics) - } - - if len(r.Ids) > 0 { - params["ids"] = strings.Join(r.Ids, ",") - } - - if r.Offsets != nil { - params["offsets"] = strconv.FormatBool(*r.Offsets) - } - - if r.Payloads != nil { - params["payloads"] = strconv.FormatBool(*r.Payloads) - } - - if r.Positions != nil { - params["positions"] = strconv.FormatBool(*r.Positions) - } - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Realtime != nil { - params["realtime"] = strconv.FormatBool(*r.Realtime) - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if r.TermStatistics != nil { - params["term_statistics"] = strconv.FormatBool(*r.TermStatistics) - } - - if r.Version != nil { - params["version"] = strconv.FormatInt(int64(*r.Version), 10) - } - - if r.VersionType != "" { - params["version_type"] = r.VersionType - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Mtermvectors) WithContext(v context.Context) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.ctx = v - } -} - -// WithBody - Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation.. -// -func (f Mtermvectors) WithBody(v io.Reader) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Body = v - } -} - -// WithIndex - the index in which the document resides.. -// -func (f Mtermvectors) WithIndex(v string) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Index = v - } -} - -// WithFields - a list of fields to return. applies to all returned documents unless otherwise specified in body "params" or "docs".. -// -func (f Mtermvectors) WithFields(v ...string) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Fields = v - } -} - -// WithFieldStatistics - specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. applies to all returned documents unless otherwise specified in body "params" or "docs".. -// -func (f Mtermvectors) WithFieldStatistics(v bool) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.FieldStatistics = &v - } -} - -// WithIds - a list of documents ids. you must define ids as parameter or set "ids" or "docs" in the request body. -// -func (f Mtermvectors) WithIds(v ...string) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Ids = v - } -} - -// WithOffsets - specifies if term offsets should be returned. applies to all returned documents unless otherwise specified in body "params" or "docs".. -// -func (f Mtermvectors) WithOffsets(v bool) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Offsets = &v - } -} - -// WithPayloads - specifies if term payloads should be returned. applies to all returned documents unless otherwise specified in body "params" or "docs".. -// -func (f Mtermvectors) WithPayloads(v bool) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Payloads = &v - } -} - -// WithPositions - specifies if term positions should be returned. applies to all returned documents unless otherwise specified in body "params" or "docs".. -// -func (f Mtermvectors) WithPositions(v bool) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Positions = &v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random) .applies to all returned documents unless otherwise specified in body "params" or "docs".. -// -func (f Mtermvectors) WithPreference(v string) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Preference = v - } -} - -// WithRealtime - specifies if requests are real-time as opposed to near-real-time (default: true).. -// -func (f Mtermvectors) WithRealtime(v bool) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Realtime = &v - } -} - -// WithRouting - specific routing value. applies to all returned documents unless otherwise specified in body "params" or "docs".. -// -func (f Mtermvectors) WithRouting(v string) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Routing = v - } -} - -// WithTermStatistics - specifies if total term frequency and document frequency should be returned. applies to all returned documents unless otherwise specified in body "params" or "docs".. -// -func (f Mtermvectors) WithTermStatistics(v bool) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.TermStatistics = &v - } -} - -// WithVersion - explicit version number for concurrency control. -// -func (f Mtermvectors) WithVersion(v int) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Version = &v - } -} - -// WithVersionType - specific version type. -// -func (f Mtermvectors) WithVersionType(v string) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.VersionType = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Mtermvectors) WithPretty() func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Mtermvectors) WithHuman() func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Mtermvectors) WithErrorTrace() func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Mtermvectors) WithFilterPath(v ...string) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Mtermvectors) WithHeader(h map[string]string) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Mtermvectors) WithOpaqueID(s string) func(*MtermvectorsRequest) { - return func(r *MtermvectorsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.nodes.hot_threads.go b/opensearchapi/api.nodes.hot_threads.go deleted file mode 100644 index d70906e7c..000000000 --- a/opensearchapi/api.nodes.hot_threads.go +++ /dev/null @@ -1,289 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newNodesHotThreadsFunc(t Transport) NodesHotThreads { - return func(o ...func(*NodesHotThreadsRequest)) (*Response, error) { - var r = NodesHotThreadsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// NodesHotThreads returns information about hot threads on each node in the cluster. -// -// -type NodesHotThreads func(o ...func(*NodesHotThreadsRequest)) (*Response, error) - -// NodesHotThreadsRequest configures the Nodes Hot Threads API request. -// -type NodesHotThreadsRequest struct { - NodeID []string - - IgnoreIdleThreads *bool - Interval time.Duration - Snapshots *int - Threads *int - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r NodesHotThreadsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_cluster") + 1 + len("nodes") + 1 + len(strings.Join(r.NodeID, ",")) + 1 + len("hot_threads")) - path.WriteString("/") - path.WriteString("_cluster") - path.WriteString("/") - path.WriteString("nodes") - if len(r.NodeID) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.NodeID, ",")) - } - path.WriteString("/") - path.WriteString("hot_threads") - - params = make(map[string]string) - - if r.IgnoreIdleThreads != nil { - params["ignore_idle_threads"] = strconv.FormatBool(*r.IgnoreIdleThreads) - } - - if r.Interval != 0 { - params["interval"] = formatDuration(r.Interval) - } - - if r.Snapshots != nil { - params["snapshots"] = strconv.FormatInt(int64(*r.Snapshots), 10) - } - - if r.Threads != nil { - params["threads"] = strconv.FormatInt(int64(*r.Threads), 10) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f NodesHotThreads) WithContext(v context.Context) func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.ctx = v - } -} - -// WithNodeID - a list of node ids or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes. -// -func (f NodesHotThreads) WithNodeID(v ...string) func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.NodeID = v - } -} - -// WithIgnoreIdleThreads - don't show threads that are in known-idle places, such as waiting on a socket select or pulling from an empty task queue (default: true). -// -func (f NodesHotThreads) WithIgnoreIdleThreads(v bool) func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.IgnoreIdleThreads = &v - } -} - -// WithInterval - the interval for the second sampling of threads. -// -func (f NodesHotThreads) WithInterval(v time.Duration) func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.Interval = v - } -} - -// WithSnapshots - number of samples of thread stacktrace (default: 10). -// -func (f NodesHotThreads) WithSnapshots(v int) func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.Snapshots = &v - } -} - -// WithThreads - specify the number of threads to provide information for (default: 3). -// -func (f NodesHotThreads) WithThreads(v int) func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.Threads = &v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f NodesHotThreads) WithTimeout(v time.Duration) func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f NodesHotThreads) WithPretty() func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f NodesHotThreads) WithHuman() func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f NodesHotThreads) WithErrorTrace() func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f NodesHotThreads) WithFilterPath(v ...string) func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f NodesHotThreads) WithHeader(h map[string]string) func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f NodesHotThreads) WithOpaqueID(s string) func(*NodesHotThreadsRequest) { - return func(r *NodesHotThreadsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.nodes.info.go b/opensearchapi/api.nodes.info.go deleted file mode 100644 index 02f604325..000000000 --- a/opensearchapi/api.nodes.info.go +++ /dev/null @@ -1,259 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newNodesInfoFunc(t Transport) NodesInfo { - return func(o ...func(*NodesInfoRequest)) (*Response, error) { - var r = NodesInfoRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// NodesInfo returns information about nodes in the cluster. -// -// -type NodesInfo func(o ...func(*NodesInfoRequest)) (*Response, error) - -// NodesInfoRequest configures the Nodes Info API request. -// -type NodesInfoRequest struct { - Metric []string - NodeID []string - - FlatSettings *bool - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r NodesInfoRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_nodes") + 1 + len(strings.Join(r.NodeID, ",")) + 1 + len(strings.Join(r.Metric, ","))) - path.WriteString("/") - path.WriteString("_nodes") - if len(r.NodeID) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.NodeID, ",")) - } - if len(r.Metric) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Metric, ",")) - } - - params = make(map[string]string) - - if r.FlatSettings != nil { - params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f NodesInfo) WithContext(v context.Context) func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - r.ctx = v - } -} - -// WithMetric - a list of metrics you wish returned. leave empty to return all.. -// -func (f NodesInfo) WithMetric(v ...string) func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - r.Metric = v - } -} - -// WithNodeID - a list of node ids or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes. -// -func (f NodesInfo) WithNodeID(v ...string) func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - r.NodeID = v - } -} - -// WithFlatSettings - return settings in flat format (default: false). -// -func (f NodesInfo) WithFlatSettings(v bool) func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - r.FlatSettings = &v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f NodesInfo) WithTimeout(v time.Duration) func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f NodesInfo) WithPretty() func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f NodesInfo) WithHuman() func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f NodesInfo) WithErrorTrace() func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f NodesInfo) WithFilterPath(v ...string) func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f NodesInfo) WithHeader(h map[string]string) func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f NodesInfo) WithOpaqueID(s string) func(*NodesInfoRequest) { - return func(r *NodesInfoRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.nodes.reload_secure_settings.go b/opensearchapi/api.nodes.reload_secure_settings.go deleted file mode 100644 index e210ba0fe..000000000 --- a/opensearchapi/api.nodes.reload_secure_settings.go +++ /dev/null @@ -1,249 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" - "time" -) - -func newNodesReloadSecureSettingsFunc(t Transport) NodesReloadSecureSettings { - return func(o ...func(*NodesReloadSecureSettingsRequest)) (*Response, error) { - var r = NodesReloadSecureSettingsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// NodesReloadSecureSettings reloads secure settings. -// -// -type NodesReloadSecureSettings func(o ...func(*NodesReloadSecureSettingsRequest)) (*Response, error) - -// NodesReloadSecureSettingsRequest configures the Nodes Reload Secure Settings API request. -// -type NodesReloadSecureSettingsRequest struct { - Body io.Reader - - NodeID []string - - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r NodesReloadSecureSettingsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_nodes") + 1 + len(strings.Join(r.NodeID, ",")) + 1 + len("reload_secure_settings")) - path.WriteString("/") - path.WriteString("_nodes") - if len(r.NodeID) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.NodeID, ",")) - } - path.WriteString("/") - path.WriteString("reload_secure_settings") - - params = make(map[string]string) - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f NodesReloadSecureSettings) WithContext(v context.Context) func(*NodesReloadSecureSettingsRequest) { - return func(r *NodesReloadSecureSettingsRequest) { - r.ctx = v - } -} - -// WithBody - An object containing the password for the opensearch keystore. -// -func (f NodesReloadSecureSettings) WithBody(v io.Reader) func(*NodesReloadSecureSettingsRequest) { - return func(r *NodesReloadSecureSettingsRequest) { - r.Body = v - } -} - -// WithNodeID - a list of node ids to span the reload/reinit call. should stay empty because reloading usually involves all cluster nodes.. -// -func (f NodesReloadSecureSettings) WithNodeID(v ...string) func(*NodesReloadSecureSettingsRequest) { - return func(r *NodesReloadSecureSettingsRequest) { - r.NodeID = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f NodesReloadSecureSettings) WithTimeout(v time.Duration) func(*NodesReloadSecureSettingsRequest) { - return func(r *NodesReloadSecureSettingsRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f NodesReloadSecureSettings) WithPretty() func(*NodesReloadSecureSettingsRequest) { - return func(r *NodesReloadSecureSettingsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f NodesReloadSecureSettings) WithHuman() func(*NodesReloadSecureSettingsRequest) { - return func(r *NodesReloadSecureSettingsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f NodesReloadSecureSettings) WithErrorTrace() func(*NodesReloadSecureSettingsRequest) { - return func(r *NodesReloadSecureSettingsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f NodesReloadSecureSettings) WithFilterPath(v ...string) func(*NodesReloadSecureSettingsRequest) { - return func(r *NodesReloadSecureSettingsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f NodesReloadSecureSettings) WithHeader(h map[string]string) func(*NodesReloadSecureSettingsRequest) { - return func(r *NodesReloadSecureSettingsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f NodesReloadSecureSettings) WithOpaqueID(s string) func(*NodesReloadSecureSettingsRequest) { - return func(r *NodesReloadSecureSettingsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.nodes.stats.go b/opensearchapi/api.nodes.stats.go deleted file mode 100644 index 80899e114..000000000 --- a/opensearchapi/api.nodes.stats.go +++ /dev/null @@ -1,365 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newNodesStatsFunc(t Transport) NodesStats { - return func(o ...func(*NodesStatsRequest)) (*Response, error) { - var r = NodesStatsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// NodesStats returns statistical information about nodes in the cluster. -// -// -type NodesStats func(o ...func(*NodesStatsRequest)) (*Response, error) - -// NodesStatsRequest configures the Nodes Stats API request. -// -type NodesStatsRequest struct { - IndexMetric []string - Metric []string - NodeID []string - - CompletionFields []string - FielddataFields []string - Fields []string - Groups *bool - IncludeSegmentFileSizes *bool - IncludeUnloadedSegments *bool - Level string - Timeout time.Duration - Types []string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r NodesStatsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_nodes") + 1 + len(strings.Join(r.NodeID, ",")) + 1 + len("stats") + 1 + len(strings.Join(r.Metric, ",")) + 1 + len(strings.Join(r.IndexMetric, ","))) - path.WriteString("/") - path.WriteString("_nodes") - if len(r.NodeID) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.NodeID, ",")) - } - path.WriteString("/") - path.WriteString("stats") - if len(r.Metric) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Metric, ",")) - } - if len(r.IndexMetric) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.IndexMetric, ",")) - } - - params = make(map[string]string) - - if len(r.CompletionFields) > 0 { - params["completion_fields"] = strings.Join(r.CompletionFields, ",") - } - - if len(r.FielddataFields) > 0 { - params["fielddata_fields"] = strings.Join(r.FielddataFields, ",") - } - - if len(r.Fields) > 0 { - params["fields"] = strings.Join(r.Fields, ",") - } - - if r.Groups != nil { - params["groups"] = strconv.FormatBool(*r.Groups) - } - - if r.IncludeSegmentFileSizes != nil { - params["include_segment_file_sizes"] = strconv.FormatBool(*r.IncludeSegmentFileSizes) - } - - if r.IncludeUnloadedSegments != nil { - params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments) - } - - if r.Level != "" { - params["level"] = r.Level - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if len(r.Types) > 0 { - params["types"] = strings.Join(r.Types, ",") - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f NodesStats) WithContext(v context.Context) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.ctx = v - } -} - -// WithIndexMetric - limit the information returned for `indices` metric to the specific index metrics. isn't used if `indices` (or `all`) metric isn't specified.. -// -func (f NodesStats) WithIndexMetric(v ...string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.IndexMetric = v - } -} - -// WithMetric - limit the information returned to the specified metrics. -// -func (f NodesStats) WithMetric(v ...string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.Metric = v - } -} - -// WithNodeID - a list of node ids or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes. -// -func (f NodesStats) WithNodeID(v ...string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.NodeID = v - } -} - -// WithCompletionFields - a list of fields for `fielddata` and `suggest` index metric (supports wildcards). -// -func (f NodesStats) WithCompletionFields(v ...string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.CompletionFields = v - } -} - -// WithFielddataFields - a list of fields for `fielddata` index metric (supports wildcards). -// -func (f NodesStats) WithFielddataFields(v ...string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.FielddataFields = v - } -} - -// WithFields - a list of fields for `fielddata` and `completion` index metric (supports wildcards). -// -func (f NodesStats) WithFields(v ...string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.Fields = v - } -} - -// WithGroups - a list of search groups for `search` index metric. -// -func (f NodesStats) WithGroups(v bool) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.Groups = &v - } -} - -// WithIncludeSegmentFileSizes - whether to report the aggregated disk usage of each one of the lucene index files (only applies if segment stats are requested). -// -func (f NodesStats) WithIncludeSegmentFileSizes(v bool) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.IncludeSegmentFileSizes = &v - } -} - -// WithIncludeUnloadedSegments - if set to true segment stats will include stats for segments that are not currently loaded into memory. -// -func (f NodesStats) WithIncludeUnloadedSegments(v bool) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.IncludeUnloadedSegments = &v - } -} - -// WithLevel - return indices stats aggregated at index, node or shard level. -// -func (f NodesStats) WithLevel(v string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.Level = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f NodesStats) WithTimeout(v time.Duration) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.Timeout = v - } -} - -// WithTypes - a list of document types for the `indexing` index metric. -// -func (f NodesStats) WithTypes(v ...string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.Types = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f NodesStats) WithPretty() func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f NodesStats) WithHuman() func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f NodesStats) WithErrorTrace() func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f NodesStats) WithFilterPath(v ...string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f NodesStats) WithHeader(h map[string]string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f NodesStats) WithOpaqueID(s string) func(*NodesStatsRequest) { - return func(r *NodesStatsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.nodes.usage.go b/opensearchapi/api.nodes.usage.go deleted file mode 100644 index 0d2d8968b..000000000 --- a/opensearchapi/api.nodes.usage.go +++ /dev/null @@ -1,247 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newNodesUsageFunc(t Transport) NodesUsage { - return func(o ...func(*NodesUsageRequest)) (*Response, error) { - var r = NodesUsageRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// NodesUsage returns low-level information about REST actions usage on nodes. -// -// -type NodesUsage func(o ...func(*NodesUsageRequest)) (*Response, error) - -// NodesUsageRequest configures the Nodes Usage API request. -// -type NodesUsageRequest struct { - Metric []string - NodeID []string - - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r NodesUsageRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_nodes") + 1 + len(strings.Join(r.NodeID, ",")) + 1 + len("usage") + 1 + len(strings.Join(r.Metric, ","))) - path.WriteString("/") - path.WriteString("_nodes") - if len(r.NodeID) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.NodeID, ",")) - } - path.WriteString("/") - path.WriteString("usage") - if len(r.Metric) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Metric, ",")) - } - - params = make(map[string]string) - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f NodesUsage) WithContext(v context.Context) func(*NodesUsageRequest) { - return func(r *NodesUsageRequest) { - r.ctx = v - } -} - -// WithMetric - limit the information returned to the specified metrics. -// -func (f NodesUsage) WithMetric(v ...string) func(*NodesUsageRequest) { - return func(r *NodesUsageRequest) { - r.Metric = v - } -} - -// WithNodeID - a list of node ids or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes. -// -func (f NodesUsage) WithNodeID(v ...string) func(*NodesUsageRequest) { - return func(r *NodesUsageRequest) { - r.NodeID = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f NodesUsage) WithTimeout(v time.Duration) func(*NodesUsageRequest) { - return func(r *NodesUsageRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f NodesUsage) WithPretty() func(*NodesUsageRequest) { - return func(r *NodesUsageRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f NodesUsage) WithHuman() func(*NodesUsageRequest) { - return func(r *NodesUsageRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f NodesUsage) WithErrorTrace() func(*NodesUsageRequest) { - return func(r *NodesUsageRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f NodesUsage) WithFilterPath(v ...string) func(*NodesUsageRequest) { - return func(r *NodesUsageRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f NodesUsage) WithHeader(h map[string]string) func(*NodesUsageRequest) { - return func(r *NodesUsageRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f NodesUsage) WithOpaqueID(s string) func(*NodesUsageRequest) { - return func(r *NodesUsageRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.ping.go b/opensearchapi/api.ping.go deleted file mode 100644 index b80ed1692..000000000 --- a/opensearchapi/api.ping.go +++ /dev/null @@ -1,202 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" -) - -func newPingFunc(t Transport) Ping { - return func(o ...func(*PingRequest)) (*Response, error) { - var r = PingRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Ping returns whether the cluster is running. -// -// -type Ping func(o ...func(*PingRequest)) (*Response, error) - -// PingRequest configures the Ping API request. -// -type PingRequest struct { - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r PingRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "HEAD" - - path.Grow(len("/")) - path.WriteString("/") - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Ping) WithContext(v context.Context) func(*PingRequest) { - return func(r *PingRequest) { - r.ctx = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Ping) WithPretty() func(*PingRequest) { - return func(r *PingRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Ping) WithHuman() func(*PingRequest) { - return func(r *PingRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Ping) WithErrorTrace() func(*PingRequest) { - return func(r *PingRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Ping) WithFilterPath(v ...string) func(*PingRequest) { - return func(r *PingRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Ping) WithHeader(h map[string]string) func(*PingRequest) { - return func(r *PingRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Ping) WithOpaqueID(s string) func(*PingRequest) { - return func(r *PingRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.pointintime.create.go b/opensearchapi/api.pointintime.create.go deleted file mode 100644 index 3a251eacf..000000000 --- a/opensearchapi/api.pointintime.create.go +++ /dev/null @@ -1,260 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "encoding/json" - "net/http" - "strings" - "time" -) - -func newPointInTimeCreateFunc(t Transport) PointInTimeCreate { - return func(o ...func(*PointInTimeCreateRequest)) (*Response, *PointInTimeCreateResp, error) { - var r = PointInTimeCreateRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// PointInTimeCreate let you create a pit for searching with pagination -type PointInTimeCreate func(o ...func(*PointInTimeCreateRequest)) (*Response, *PointInTimeCreateResp, error) - -// PointInTimeCreateRequest configures the Point In Time Create API request. -type PointInTimeCreateRequest struct { - Index []string - - KeepAlive time.Duration - Preference string - Routing string - ExpandWildcards string - AllowPartialPitCreation bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// PointInTimeCreateResp is a custom type to parse the Point In Time Create Reponse -type PointInTimeCreateResp struct { - PitID string `json:"pit_id"` - Shards struct { - Total int `json:"total"` - Successful int `json:"successful"` - Skipped int `json:"skipped"` - Failed int `json:"failed"` - } `json:"_shards"` - CreationTime int `json:"creation_time"` -} - -// Do executes the request and returns response, PointInTimeCreateResp and error. -func (r PointInTimeCreateRequest) Do(ctx context.Context, transport Transport) (*Response, *PointInTimeCreateResp, error) { - var ( - path strings.Builder - params map[string]string - - data PointInTimeCreateResp - ) - method := "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + len("/_search/point_in_time")) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - path.WriteString("/_search/point_in_time") - - params = make(map[string]string) - - if r.KeepAlive != 0 { - params["keep_alive"] = formatDuration(r.KeepAlive) - } - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.AllowPartialPitCreation { - params["allow_partial_pit_creation"] = "true" - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - if err = response.Err(); err != nil { - return &response, nil, err - } - - if len(r.FilterPath) != 0 { - return &response, nil, nil - } - - if err := json.NewDecoder(response.Body).Decode(&data); err != nil { - return &response, nil, err - } - return &response, &data, nil -} - -// WithIndex - a list of index names to search; use _all to perform the operation on all indices. -func (f PointInTimeCreate) WithIndex(v ...string) func(*PointInTimeCreateRequest) { - return func(r *PointInTimeCreateRequest) { - r.Index = v - } -} - -// WithContext sets the request context. -func (f PointInTimeCreate) WithContext(v context.Context) func(*PointInTimeCreateRequest) { - return func(r *PointInTimeCreateRequest) { - r.ctx = v - } -} - -// WithKeepAlive - specify the amount of time to keep the PIT. -func (f PointInTimeCreate) WithKeepAlive(v time.Duration) func(*PointInTimeCreateRequest) { - return func(r *PointInTimeCreateRequest) { - r.KeepAlive = v - } -} - -// WithPretty makes the response body pretty-printed. -func (f PointInTimeCreate) WithPretty() func(*PointInTimeCreateRequest) { - return func(r *PointInTimeCreateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -func (f PointInTimeCreate) WithHuman() func(*PointInTimeCreateRequest) { - return func(r *PointInTimeCreateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -func (f PointInTimeCreate) WithErrorTrace() func(*PointInTimeCreateRequest) { - return func(r *PointInTimeCreateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -func (f PointInTimeCreate) WithFilterPath(v ...string) func(*PointInTimeCreateRequest) { - return func(r *PointInTimeCreateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -func (f PointInTimeCreate) WithHeader(h map[string]string) func(*PointInTimeCreateRequest) { - return func(r *PointInTimeCreateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -func (f PointInTimeCreate) WithOpaqueID(s string) func(*PointInTimeCreateRequest) { - return func(r *PointInTimeCreateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.pointintime.delete.go b/opensearchapi/api.pointintime.delete.go deleted file mode 100644 index ede0ec01a..000000000 --- a/opensearchapi/api.pointintime.delete.go +++ /dev/null @@ -1,241 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "bytes" - "context" - "encoding/json" - "io" - "net/http" - "strings" -) - -func newPointInTimeDeleteFunc(t Transport) PointInTimeDelete { - return func(o ...func(*PointInTimeDeleteRequest)) (*Response, *PointInTimeDeleteResp, error) { - var r = PointInTimeDeleteRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// PointInTimeDelete lets you delete pits used for searching with pagination -type PointInTimeDelete func(o ...func(*PointInTimeDeleteRequest)) (*Response, *PointInTimeDeleteResp, error) - -// PointInTimeDeleteRequest configures the Point In Time Delete API request. -type PointInTimeDeleteRequest struct { - PitID []string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// PointInTimeDeleteRequestBody is used to from the delete request body -type PointInTimeDeleteRequestBody struct { - PitID []string `json:"pit_id"` -} - -// PointInTimeDeleteResp is a custom type to parse the Point In Time Delete Reponse -type PointInTimeDeleteResp struct { - Pits []struct { - PitID string `json:"pit_id"` - Successful bool `json:"successful"` - } `json:"pits"` -} - -// Do executes the request and returns response or error. -func (r PointInTimeDeleteRequest) Do(ctx context.Context, transport Transport) (*Response, *PointInTimeDeleteResp, error) { - var ( - path strings.Builder - params map[string]string - body io.Reader - - data PointInTimeDeleteResp - ) - method := "DELETE" - - path.Grow(len("/_search/point_in_time")) - path.WriteString("/_search/point_in_time") - - params = make(map[string]string) - - if len(r.PitID) > 0 { - bodyStruct := PointInTimeDeleteRequestBody{PitID: r.PitID} - bodyJSON, err := json.Marshal(bodyStruct) - if err != nil { - return nil, nil, err - } - body = bytes.NewBuffer(bodyJSON) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), body) - if err != nil { - return nil, nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - if err = response.Err(); err != nil { - return &response, nil, err - } - - if len(r.FilterPath) != 0 { - return &response, nil, nil - } - - if err := json.NewDecoder(response.Body).Decode(&data); err != nil { - return &response, nil, err - } - return &response, &data, nil -} - -// WithPitID sets the Pit to delete. -func (f PointInTimeDelete) WithPitID(v ...string) func(*PointInTimeDeleteRequest) { - return func(r *PointInTimeDeleteRequest) { - r.PitID = v - } -} - -// WithContext sets the request context. -func (f PointInTimeDelete) WithContext(v context.Context) func(*PointInTimeDeleteRequest) { - return func(r *PointInTimeDeleteRequest) { - r.ctx = v - } -} - -// WithPretty makes the response body pretty-printed. -func (f PointInTimeDelete) WithPretty() func(*PointInTimeDeleteRequest) { - return func(r *PointInTimeDeleteRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -func (f PointInTimeDelete) WithHuman() func(*PointInTimeDeleteRequest) { - return func(r *PointInTimeDeleteRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -func (f PointInTimeDelete) WithErrorTrace() func(*PointInTimeDeleteRequest) { - return func(r *PointInTimeDeleteRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -func (f PointInTimeDelete) WithFilterPath(v ...string) func(*PointInTimeDeleteRequest) { - return func(r *PointInTimeDeleteRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -func (f PointInTimeDelete) WithHeader(h map[string]string) func(*PointInTimeDeleteRequest) { - return func(r *PointInTimeDeleteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -func (f PointInTimeDelete) WithOpaqueID(s string) func(*PointInTimeDeleteRequest) { - return func(r *PointInTimeDeleteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.pointintime.get.go b/opensearchapi/api.pointintime.get.go deleted file mode 100644 index d972380cc..000000000 --- a/opensearchapi/api.pointintime.get.go +++ /dev/null @@ -1,213 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "encoding/json" - "net/http" - "strings" - "time" -) - -func newPointInTimeGetFunc(t Transport) PointInTimeGet { - return func(o ...func(*PointInTimeGetRequest)) (*Response, *PointInTimeGetResp, error) { - var r = PointInTimeGetRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// PointInTimeGet lets you get all existing pits -type PointInTimeGet func(o ...func(*PointInTimeGetRequest)) (*Response, *PointInTimeGetResp, error) - -// PointInTimeGetRequest configures the Point In Time Get API request. -type PointInTimeGetRequest struct { - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// PointInTimeGetResp is a custom type to parse the Point In Time Get Reponse -type PointInTimeGetResp struct { - Pits []struct { - PitID string `json:"pit_id"` - CreationTime int `json:"creation_time"` - KeepAlive time.Duration `json:"keep_alive"` - } `json:"pits"` -} - -// Do executes the request and returns response or error. -func (r PointInTimeGetRequest) Do(ctx context.Context, transport Transport) (*Response, *PointInTimeGetResp, error) { - var ( - path strings.Builder - params map[string]string - - data PointInTimeGetResp - ) - method := "GET" - - path.Grow(len("/_search/point_in_time/_all")) - path.WriteString("/_search/point_in_time/_all") - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - if err = response.Err(); err != nil { - return &response, nil, err - } - - if len(r.FilterPath) != 0 { - return &response, nil, nil - } - - if err := json.NewDecoder(response.Body).Decode(&data); err != nil { - return &response, nil, err - } - return &response, &data, nil -} - -// WithContext sets the request context. -func (f PointInTimeGet) WithContext(v context.Context) func(*PointInTimeGetRequest) { - return func(r *PointInTimeGetRequest) { - r.ctx = v - } -} - -// WithPretty makes the response body pretty-printed. -func (f PointInTimeGet) WithPretty() func(*PointInTimeGetRequest) { - return func(r *PointInTimeGetRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -func (f PointInTimeGet) WithHuman() func(*PointInTimeGetRequest) { - return func(r *PointInTimeGetRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -func (f PointInTimeGet) WithErrorTrace() func(*PointInTimeGetRequest) { - return func(r *PointInTimeGetRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -func (f PointInTimeGet) WithFilterPath(v ...string) func(*PointInTimeGetRequest) { - return func(r *PointInTimeGetRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -func (f PointInTimeGet) WithHeader(h map[string]string) func(*PointInTimeGetRequest) { - return func(r *PointInTimeGetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -func (f PointInTimeGet) WithOpaqueID(s string) func(*PointInTimeGetRequest) { - return func(r *PointInTimeGetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.put_script.go b/opensearchapi/api.put_script.go deleted file mode 100644 index c8dea2dad..000000000 --- a/opensearchapi/api.put_script.go +++ /dev/null @@ -1,275 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" - "time" -) - -func newPutScriptFunc(t Transport) PutScript { - return func(id string, body io.Reader, o ...func(*PutScriptRequest)) (*Response, error) { - var r = PutScriptRequest{ScriptID: id, Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// PutScript creates or updates a script. -// -// -type PutScript func(id string, body io.Reader, o ...func(*PutScriptRequest)) (*Response, error) - -// PutScriptRequest configures the Put Script API request. -// -type PutScriptRequest struct { - ScriptID string - - Body io.Reader - - ScriptContext string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r PutScriptRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len("_scripts") + 1 + len(r.ScriptID) + 1 + len(r.ScriptContext)) - path.WriteString("/") - path.WriteString("_scripts") - path.WriteString("/") - path.WriteString(r.ScriptID) - if r.ScriptContext != "" { - path.WriteString("/") - path.WriteString(r.ScriptContext) - } - - params = make(map[string]string) - - if r.ScriptContext != "" { - params["context"] = r.ScriptContext - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f PutScript) WithContext(v context.Context) func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - r.ctx = v - } -} - -// WithScriptContext - script context. -// -func (f PutScript) WithScriptContext(v string) func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - r.ScriptContext = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f PutScript) WithMasterTimeout(v time.Duration) func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f PutScript) WithClusterManagerTimeout(v time.Duration) func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f PutScript) WithTimeout(v time.Duration) func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f PutScript) WithPretty() func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f PutScript) WithHuman() func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f PutScript) WithErrorTrace() func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f PutScript) WithFilterPath(v ...string) func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f PutScript) WithHeader(h map[string]string) func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f PutScript) WithOpaqueID(s string) func(*PutScriptRequest) { - return func(r *PutScriptRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.rank_eval.go b/opensearchapi/api.rank_eval.go deleted file mode 100644 index 94489a2d9..000000000 --- a/opensearchapi/api.rank_eval.go +++ /dev/null @@ -1,280 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newRankEvalFunc(t Transport) RankEval { - return func(body io.Reader, o ...func(*RankEvalRequest)) (*Response, error) { - var r = RankEvalRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// RankEval allows to evaluate the quality of ranked search results over a set of typical search queries -// -// This API is experimental. -// -// -type RankEval func(body io.Reader, o ...func(*RankEvalRequest)) (*Response, error) - -// RankEvalRequest configures the Rank Eval API request. -// -type RankEvalRequest struct { - Index []string - - Body io.Reader - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - SearchType string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r RankEvalRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_rank_eval")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_rank_eval") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.SearchType != "" { - params["search_type"] = r.SearchType - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f RankEval) WithContext(v context.Context) func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to search; use _all to perform the operation on all indices. -// -func (f RankEval) WithIndex(v ...string) func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f RankEval) WithAllowNoIndices(v bool) func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f RankEval) WithExpandWildcards(v string) func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f RankEval) WithIgnoreUnavailable(v bool) func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithSearchType - search operation type. -// -func (f RankEval) WithSearchType(v string) func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - r.SearchType = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f RankEval) WithPretty() func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f RankEval) WithHuman() func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f RankEval) WithErrorTrace() func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f RankEval) WithFilterPath(v ...string) func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f RankEval) WithHeader(h map[string]string) func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f RankEval) WithOpaqueID(s string) func(*RankEvalRequest) { - return func(r *RankEvalRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.reindex.go b/opensearchapi/api.reindex.go deleted file mode 100644 index 0bccd5160..000000000 --- a/opensearchapi/api.reindex.go +++ /dev/null @@ -1,319 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "fmt" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newReindexFunc(t Transport) Reindex { - return func(body io.Reader, o ...func(*ReindexRequest)) (*Response, error) { - var r = ReindexRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Reindex allows to copy documents from one index to another, optionally filtering the source -// documents by a query, changing the destination index settings, or fetching the -// documents from a remote cluster. -// -// -type Reindex func(body io.Reader, o ...func(*ReindexRequest)) (*Response, error) - -// ReindexRequest configures the Reindex API request. -// -type ReindexRequest struct { - Body io.Reader - - MaxDocs *int - Refresh *bool - RequestsPerSecond *int - Scroll time.Duration - Slices interface{} - Timeout time.Duration - WaitForActiveShards string - WaitForCompletion *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ReindexRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(len("/_reindex")) - path.WriteString("/_reindex") - - params = make(map[string]string) - - if r.MaxDocs != nil { - params["max_docs"] = strconv.FormatInt(int64(*r.MaxDocs), 10) - } - - if r.Refresh != nil { - params["refresh"] = strconv.FormatBool(*r.Refresh) - } - - if r.RequestsPerSecond != nil { - params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) - } - - if r.Scroll != 0 { - params["scroll"] = formatDuration(r.Scroll) - } - - if r.Slices != nil { - params["slices"] = fmt.Sprintf("%v", r.Slices) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.WaitForCompletion != nil { - params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Reindex) WithContext(v context.Context) func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.ctx = v - } -} - -// WithMaxDocs - maximum number of documents to process (default: all documents). -// -func (f Reindex) WithMaxDocs(v int) func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.MaxDocs = &v - } -} - -// WithRefresh - should the affected indexes be refreshed?. -// -func (f Reindex) WithRefresh(v bool) func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.Refresh = &v - } -} - -// WithRequestsPerSecond - the throttle to set on this request in sub-requests per second. -1 means no throttle.. -// -func (f Reindex) WithRequestsPerSecond(v int) func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.RequestsPerSecond = &v - } -} - -// WithScroll - control how long to keep the search context alive. -// -func (f Reindex) WithScroll(v time.Duration) func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.Scroll = v - } -} - -// WithSlices - the number of slices this task should be divided into. defaults to 1, meaning the task isn't sliced into subtasks. can be set to `auto`.. -// -func (f Reindex) WithSlices(v interface{}) func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.Slices = v - } -} - -// WithTimeout - time each individual bulk request should wait for shards that are unavailable.. -// -func (f Reindex) WithTimeout(v time.Duration) func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the reindex operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1). -// -func (f Reindex) WithWaitForActiveShards(v string) func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.WaitForActiveShards = v - } -} - -// WithWaitForCompletion - should the request should block until the reindex is complete.. -// -func (f Reindex) WithWaitForCompletion(v bool) func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.WaitForCompletion = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Reindex) WithPretty() func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Reindex) WithHuman() func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Reindex) WithErrorTrace() func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Reindex) WithFilterPath(v ...string) func(*ReindexRequest) { - return func(r *ReindexRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Reindex) WithHeader(h map[string]string) func(*ReindexRequest) { - return func(r *ReindexRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Reindex) WithOpaqueID(s string) func(*ReindexRequest) { - return func(r *ReindexRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.reindex_rethrottle.go b/opensearchapi/api.reindex_rethrottle.go deleted file mode 100644 index bc4fb5588..000000000 --- a/opensearchapi/api.reindex_rethrottle.go +++ /dev/null @@ -1,224 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newReindexRethrottleFunc(t Transport) ReindexRethrottle { - return func(task_id string, requests_per_second *int, o ...func(*ReindexRethrottleRequest)) (*Response, error) { - var r = ReindexRethrottleRequest{TaskID: task_id, RequestsPerSecond: requests_per_second} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ReindexRethrottle changes the number of requests per second for a particular Reindex operation. -// -// -type ReindexRethrottle func(task_id string, requests_per_second *int, o ...func(*ReindexRethrottleRequest)) (*Response, error) - -// ReindexRethrottleRequest configures the Reindex Rethrottle API request. -// -type ReindexRethrottleRequest struct { - TaskID string - - RequestsPerSecond *int - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ReindexRethrottleRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_reindex") + 1 + len(r.TaskID) + 1 + len("_rethrottle")) - path.WriteString("/") - path.WriteString("_reindex") - path.WriteString("/") - path.WriteString(r.TaskID) - path.WriteString("/") - path.WriteString("_rethrottle") - - params = make(map[string]string) - - if r.RequestsPerSecond != nil { - params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ReindexRethrottle) WithContext(v context.Context) func(*ReindexRethrottleRequest) { - return func(r *ReindexRethrottleRequest) { - r.ctx = v - } -} - -// WithRequestsPerSecond - the throttle to set on this request in floating sub-requests per second. -1 means set no throttle.. -// -func (f ReindexRethrottle) WithRequestsPerSecond(v int) func(*ReindexRethrottleRequest) { - return func(r *ReindexRethrottleRequest) { - r.RequestsPerSecond = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ReindexRethrottle) WithPretty() func(*ReindexRethrottleRequest) { - return func(r *ReindexRethrottleRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ReindexRethrottle) WithHuman() func(*ReindexRethrottleRequest) { - return func(r *ReindexRethrottleRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ReindexRethrottle) WithErrorTrace() func(*ReindexRethrottleRequest) { - return func(r *ReindexRethrottleRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ReindexRethrottle) WithFilterPath(v ...string) func(*ReindexRethrottleRequest) { - return func(r *ReindexRethrottleRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ReindexRethrottle) WithHeader(h map[string]string) func(*ReindexRethrottleRequest) { - return func(r *ReindexRethrottleRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ReindexRethrottle) WithOpaqueID(s string) func(*ReindexRethrottleRequest) { - return func(r *ReindexRethrottleRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.render_search_template.go b/opensearchapi/api.render_search_template.go deleted file mode 100644 index 02a293a12..000000000 --- a/opensearchapi/api.render_search_template.go +++ /dev/null @@ -1,234 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" -) - -func newRenderSearchTemplateFunc(t Transport) RenderSearchTemplate { - return func(o ...func(*RenderSearchTemplateRequest)) (*Response, error) { - var r = RenderSearchTemplateRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// RenderSearchTemplate allows to use the Mustache language to pre-render a search definition. -// -// -type RenderSearchTemplate func(o ...func(*RenderSearchTemplateRequest)) (*Response, error) - -// RenderSearchTemplateRequest configures the Render Search Template API request. -// -type RenderSearchTemplateRequest struct { - TemplateID string - - Body io.Reader - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r RenderSearchTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_render") + 1 + len("template") + 1 + len(r.TemplateID)) - path.WriteString("/") - path.WriteString("_render") - path.WriteString("/") - path.WriteString("template") - if r.TemplateID != "" { - path.WriteString("/") - path.WriteString(r.TemplateID) - } - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f RenderSearchTemplate) WithContext(v context.Context) func(*RenderSearchTemplateRequest) { - return func(r *RenderSearchTemplateRequest) { - r.ctx = v - } -} - -// WithBody - The search definition template and its params. -// -func (f RenderSearchTemplate) WithBody(v io.Reader) func(*RenderSearchTemplateRequest) { - return func(r *RenderSearchTemplateRequest) { - r.Body = v - } -} - -// WithTemplateID - the ID of the stored search template. -// -func (f RenderSearchTemplate) WithTemplateID(v string) func(*RenderSearchTemplateRequest) { - return func(r *RenderSearchTemplateRequest) { - r.TemplateID = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f RenderSearchTemplate) WithPretty() func(*RenderSearchTemplateRequest) { - return func(r *RenderSearchTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f RenderSearchTemplate) WithHuman() func(*RenderSearchTemplateRequest) { - return func(r *RenderSearchTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f RenderSearchTemplate) WithErrorTrace() func(*RenderSearchTemplateRequest) { - return func(r *RenderSearchTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f RenderSearchTemplate) WithFilterPath(v ...string) func(*RenderSearchTemplateRequest) { - return func(r *RenderSearchTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f RenderSearchTemplate) WithHeader(h map[string]string) func(*RenderSearchTemplateRequest) { - return func(r *RenderSearchTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f RenderSearchTemplate) WithOpaqueID(s string) func(*RenderSearchTemplateRequest) { - return func(r *RenderSearchTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.scripts_painless_execute.go b/opensearchapi/api.scripts_painless_execute.go deleted file mode 100644 index 2c26c3d3e..000000000 --- a/opensearchapi/api.scripts_painless_execute.go +++ /dev/null @@ -1,219 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" -) - -func newScriptsPainlessExecuteFunc(t Transport) ScriptsPainlessExecute { - return func(o ...func(*ScriptsPainlessExecuteRequest)) (*Response, error) { - var r = ScriptsPainlessExecuteRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// ScriptsPainlessExecute allows an arbitrary script to be executed and a result to be returned -// -// This API is experimental. -// -// -type ScriptsPainlessExecute func(o ...func(*ScriptsPainlessExecuteRequest)) (*Response, error) - -// ScriptsPainlessExecuteRequest configures the Scripts Painless Execute API request. -// -type ScriptsPainlessExecuteRequest struct { - Body io.Reader - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ScriptsPainlessExecuteRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(len("/_scripts/painless/_execute")) - path.WriteString("/_scripts/painless/_execute") - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f ScriptsPainlessExecute) WithContext(v context.Context) func(*ScriptsPainlessExecuteRequest) { - return func(r *ScriptsPainlessExecuteRequest) { - r.ctx = v - } -} - -// WithBody - The script to execute. -// -func (f ScriptsPainlessExecute) WithBody(v io.Reader) func(*ScriptsPainlessExecuteRequest) { - return func(r *ScriptsPainlessExecuteRequest) { - r.Body = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f ScriptsPainlessExecute) WithPretty() func(*ScriptsPainlessExecuteRequest) { - return func(r *ScriptsPainlessExecuteRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f ScriptsPainlessExecute) WithHuman() func(*ScriptsPainlessExecuteRequest) { - return func(r *ScriptsPainlessExecuteRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f ScriptsPainlessExecute) WithErrorTrace() func(*ScriptsPainlessExecuteRequest) { - return func(r *ScriptsPainlessExecuteRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f ScriptsPainlessExecute) WithFilterPath(v ...string) func(*ScriptsPainlessExecuteRequest) { - return func(r *ScriptsPainlessExecuteRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f ScriptsPainlessExecute) WithHeader(h map[string]string) func(*ScriptsPainlessExecuteRequest) { - return func(r *ScriptsPainlessExecuteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f ScriptsPainlessExecute) WithOpaqueID(s string) func(*ScriptsPainlessExecuteRequest) { - return func(r *ScriptsPainlessExecuteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.scroll.go b/opensearchapi/api.scroll.go deleted file mode 100644 index f6b5e28d3..000000000 --- a/opensearchapi/api.scroll.go +++ /dev/null @@ -1,260 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newScrollFunc(t Transport) Scroll { - return func(o ...func(*ScrollRequest)) (*Response, error) { - var r = ScrollRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Scroll allows to retrieve a large numbers of results from a single search request. -// -// -type Scroll func(o ...func(*ScrollRequest)) (*Response, error) - -// ScrollRequest configures the Scroll API request. -// -type ScrollRequest struct { - Body io.Reader - - ScrollID string - - RestTotalHitsAsInt *bool - Scroll time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r ScrollRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(len("/_search/scroll")) - path.WriteString("/_search/scroll") - - params = make(map[string]string) - - if r.RestTotalHitsAsInt != nil { - params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) - } - - if r.Scroll != 0 { - params["scroll"] = formatDuration(r.Scroll) - } - - if r.ScrollID != "" { - params["scroll_id"] = r.ScrollID - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Scroll) WithContext(v context.Context) func(*ScrollRequest) { - return func(r *ScrollRequest) { - r.ctx = v - } -} - -// WithBody - The scroll ID if not passed by URL or query parameter.. -// -func (f Scroll) WithBody(v io.Reader) func(*ScrollRequest) { - return func(r *ScrollRequest) { - r.Body = v - } -} - -// WithScrollID - the scroll ID. -// -func (f Scroll) WithScrollID(v string) func(*ScrollRequest) { - return func(r *ScrollRequest) { - r.ScrollID = v - } -} - -// WithRestTotalHitsAsInt - indicates whether hits.total should be rendered as an integer or an object in the rest search response. -// -func (f Scroll) WithRestTotalHitsAsInt(v bool) func(*ScrollRequest) { - return func(r *ScrollRequest) { - r.RestTotalHitsAsInt = &v - } -} - -// WithScroll - specify how long a consistent view of the index should be maintained for scrolled search. -// -func (f Scroll) WithScroll(v time.Duration) func(*ScrollRequest) { - return func(r *ScrollRequest) { - r.Scroll = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Scroll) WithPretty() func(*ScrollRequest) { - return func(r *ScrollRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Scroll) WithHuman() func(*ScrollRequest) { - return func(r *ScrollRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Scroll) WithErrorTrace() func(*ScrollRequest) { - return func(r *ScrollRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Scroll) WithFilterPath(v ...string) func(*ScrollRequest) { - return func(r *ScrollRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Scroll) WithHeader(h map[string]string) func(*ScrollRequest) { - return func(r *ScrollRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Scroll) WithOpaqueID(s string) func(*ScrollRequest) { - return func(r *ScrollRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.search.go b/opensearchapi/api.search.go deleted file mode 100644 index ca2c59291..000000000 --- a/opensearchapi/api.search.go +++ /dev/null @@ -1,799 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "fmt" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newSearchFunc(t Transport) Search { - return func(o ...func(*SearchRequest)) (*Response, error) { - var r = SearchRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Search returns results matching a query. -// -// -type Search func(o ...func(*SearchRequest)) (*Response, error) - -// SearchRequest configures the Search API request. -// -type SearchRequest struct { - Index []string - - Body io.Reader - - AllowNoIndices *bool - AllowPartialSearchResults *bool - Analyzer string - AnalyzeWildcard *bool - BatchedReduceSize *int - CcsMinimizeRoundtrips *bool - DefaultOperator string - Df string - DocvalueFields []string - ExpandWildcards string - Explain *bool - From *int - IgnoreThrottled *bool - IgnoreUnavailable *bool - Lenient *bool - MaxConcurrentShardRequests *int - MinCompatibleShardNode string - Preference string - PreFilterShardSize *int - Query string - RequestCache *bool - RestTotalHitsAsInt *bool - Routing []string - Scroll time.Duration - SearchType string - SeqNoPrimaryTerm *bool - Size *int - Sort []string - Source interface{} - SourceExcludes []string - SourceIncludes []string - Stats []string - StoredFields []string - SuggestField string - SuggestMode string - SuggestSize *int - SuggestText string - TerminateAfter *int - Timeout time.Duration - TrackScores *bool - TrackTotalHits interface{} - TypedKeys *bool - Version *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SearchRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_search")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_search") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.AllowPartialSearchResults != nil { - params["allow_partial_search_results"] = strconv.FormatBool(*r.AllowPartialSearchResults) - } - - if r.Analyzer != "" { - params["analyzer"] = r.Analyzer - } - - if r.AnalyzeWildcard != nil { - params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) - } - - if r.BatchedReduceSize != nil { - params["batched_reduce_size"] = strconv.FormatInt(int64(*r.BatchedReduceSize), 10) - } - - if r.CcsMinimizeRoundtrips != nil { - params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) - } - - if r.DefaultOperator != "" { - params["default_operator"] = r.DefaultOperator - } - - if r.Df != "" { - params["df"] = r.Df - } - - if len(r.DocvalueFields) > 0 { - params["docvalue_fields"] = strings.Join(r.DocvalueFields, ",") - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Explain != nil { - params["explain"] = strconv.FormatBool(*r.Explain) - } - - if r.From != nil { - params["from"] = strconv.FormatInt(int64(*r.From), 10) - } - - if r.IgnoreThrottled != nil { - params["ignore_throttled"] = strconv.FormatBool(*r.IgnoreThrottled) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Lenient != nil { - params["lenient"] = strconv.FormatBool(*r.Lenient) - } - - if r.MaxConcurrentShardRequests != nil { - params["max_concurrent_shard_requests"] = strconv.FormatInt(int64(*r.MaxConcurrentShardRequests), 10) - } - - if r.MinCompatibleShardNode != "" { - params["min_compatible_shard_node"] = r.MinCompatibleShardNode - } - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.PreFilterShardSize != nil { - params["pre_filter_shard_size"] = strconv.FormatInt(int64(*r.PreFilterShardSize), 10) - } - - if r.Query != "" { - params["q"] = r.Query - } - - if r.RequestCache != nil { - params["request_cache"] = strconv.FormatBool(*r.RequestCache) - } - - if r.RestTotalHitsAsInt != nil { - params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) - } - - if len(r.Routing) > 0 { - params["routing"] = strings.Join(r.Routing, ",") - } - - if r.Scroll != 0 { - params["scroll"] = formatDuration(r.Scroll) - } - - if r.SearchType != "" { - params["search_type"] = r.SearchType - } - - if r.SeqNoPrimaryTerm != nil { - params["seq_no_primary_term"] = strconv.FormatBool(*r.SeqNoPrimaryTerm) - } - - if r.Size != nil { - params["size"] = strconv.FormatInt(int64(*r.Size), 10) - } - - if len(r.Sort) > 0 { - params["sort"] = strings.Join(r.Sort, ",") - } - - if source, ok := r.Source.(bool); ok { - params["_source"] = strconv.FormatBool(source) - } else if source, ok := r.Source.(string); ok && source != "" { - params["_source"] = source - } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { - params["_source"] = strings.Join(sources, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if len(r.Stats) > 0 { - params["stats"] = strings.Join(r.Stats, ",") - } - - if len(r.StoredFields) > 0 { - params["stored_fields"] = strings.Join(r.StoredFields, ",") - } - - if r.SuggestField != "" { - params["suggest_field"] = r.SuggestField - } - - if r.SuggestMode != "" { - params["suggest_mode"] = r.SuggestMode - } - - if r.SuggestSize != nil { - params["suggest_size"] = strconv.FormatInt(int64(*r.SuggestSize), 10) - } - - if r.SuggestText != "" { - params["suggest_text"] = r.SuggestText - } - - if r.TerminateAfter != nil { - params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.TrackScores != nil { - params["track_scores"] = strconv.FormatBool(*r.TrackScores) - } - - if r.TrackTotalHits != nil { - params["track_total_hits"] = fmt.Sprintf("%v", r.TrackTotalHits) - } - - if r.TypedKeys != nil { - params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) - } - - if r.Version != nil { - params["version"] = strconv.FormatBool(*r.Version) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Search) WithContext(v context.Context) func(*SearchRequest) { - return func(r *SearchRequest) { - r.ctx = v - } -} - -// WithBody - The search definition using the Query DSL. -// -func (f Search) WithBody(v io.Reader) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Body = v - } -} - -// WithIndex - a list of index names to search; use _all to perform the operation on all indices. -// -func (f Search) WithIndex(v ...string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f Search) WithAllowNoIndices(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.AllowNoIndices = &v - } -} - -// WithAllowPartialSearchResults - indicate if an error should be returned if there is a partial search failure or timeout. -// -func (f Search) WithAllowPartialSearchResults(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.AllowPartialSearchResults = &v - } -} - -// WithAnalyzer - the analyzer to use for the query string. -// -func (f Search) WithAnalyzer(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Analyzer = v - } -} - -// WithAnalyzeWildcard - specify whether wildcard and prefix queries should be analyzed (default: false). -// -func (f Search) WithAnalyzeWildcard(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.AnalyzeWildcard = &v - } -} - -// WithBatchedReduceSize - the number of shard results that should be reduced at once on the coordinating node. this value should be used as a protection mechanism to reduce the memory overhead per search request if the potential number of shards in the request can be large.. -// -func (f Search) WithBatchedReduceSize(v int) func(*SearchRequest) { - return func(r *SearchRequest) { - r.BatchedReduceSize = &v - } -} - -// WithCcsMinimizeRoundtrips - indicates whether network round-trips should be minimized as part of cross-cluster search requests execution. -// -func (f Search) WithCcsMinimizeRoundtrips(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.CcsMinimizeRoundtrips = &v - } -} - -// WithDefaultOperator - the default operator for query string query (and or or). -// -func (f Search) WithDefaultOperator(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.DefaultOperator = v - } -} - -// WithDf - the field to use as default where no field prefix is given in the query string. -// -func (f Search) WithDf(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Df = v - } -} - -// WithDocvalueFields - a list of fields to return as the docvalue representation of a field for each hit. -// -func (f Search) WithDocvalueFields(v ...string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.DocvalueFields = v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f Search) WithExpandWildcards(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.ExpandWildcards = v - } -} - -// WithExplain - specify whether to return detailed information about score computation as part of a hit. -// -func (f Search) WithExplain(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Explain = &v - } -} - -// WithFrom - starting offset (default: 0). -// -func (f Search) WithFrom(v int) func(*SearchRequest) { - return func(r *SearchRequest) { - r.From = &v - } -} - -// WithIgnoreThrottled - whether specified concrete, expanded or aliased indices should be ignored when throttled. -// -func (f Search) WithIgnoreThrottled(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.IgnoreThrottled = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f Search) WithIgnoreUnavailable(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithLenient - specify whether format-based query failures (such as providing text to a numeric field) should be ignored. -// -func (f Search) WithLenient(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Lenient = &v - } -} - -// WithMaxConcurrentShardRequests - the number of concurrent shard requests per node this search executes concurrently. this value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests. -// -func (f Search) WithMaxConcurrentShardRequests(v int) func(*SearchRequest) { - return func(r *SearchRequest) { - r.MaxConcurrentShardRequests = &v - } -} - -// WithMinCompatibleShardNode - the minimum compatible version that all shards involved in search should have for this request to be successful. -// -func (f Search) WithMinCompatibleShardNode(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.MinCompatibleShardNode = v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f Search) WithPreference(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Preference = v - } -} - -// WithPreFilterShardSize - a threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. this filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on its rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint.. -// -func (f Search) WithPreFilterShardSize(v int) func(*SearchRequest) { - return func(r *SearchRequest) { - r.PreFilterShardSize = &v - } -} - -// WithQuery - query in the lucene query string syntax. -// -func (f Search) WithQuery(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Query = v - } -} - -// WithRequestCache - specify if request cache should be used for this request or not, defaults to index level setting. -// -func (f Search) WithRequestCache(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.RequestCache = &v - } -} - -// WithRestTotalHitsAsInt - indicates whether hits.total should be rendered as an integer or an object in the rest search response. -// -func (f Search) WithRestTotalHitsAsInt(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.RestTotalHitsAsInt = &v - } -} - -// WithRouting - a list of specific routing values. -// -func (f Search) WithRouting(v ...string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Routing = v - } -} - -// WithScroll - specify how long a consistent view of the index should be maintained for scrolled search. -// -func (f Search) WithScroll(v time.Duration) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Scroll = v - } -} - -// WithSearchType - search operation type. -// -func (f Search) WithSearchType(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.SearchType = v - } -} - -// WithSeqNoPrimaryTerm - specify whether to return sequence number and primary term of the last modification of each hit. -// -func (f Search) WithSeqNoPrimaryTerm(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.SeqNoPrimaryTerm = &v - } -} - -// WithSize - number of hits to return (default: 10). -// -func (f Search) WithSize(v int) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Size = &v - } -} - -// WithSort - a list of : pairs. -// -func (f Search) WithSort(v ...string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Sort = v - } -} - -// WithSource - true or false to return the _source field or not, or a list of fields to return. -// -func (f Search) WithSource(v interface{}) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Source = v - } -} - -// WithSourceExcludes - a list of fields to exclude from the returned _source field. -// -func (f Search) WithSourceExcludes(v ...string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - a list of fields to extract and return from the _source field. -// -func (f Search) WithSourceIncludes(v ...string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.SourceIncludes = v - } -} - -// WithStats - specific 'tag' of the request for logging and statistical purposes. -// -func (f Search) WithStats(v ...string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Stats = v - } -} - -// WithStoredFields - a list of stored fields to return as part of a hit. -// -func (f Search) WithStoredFields(v ...string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.StoredFields = v - } -} - -// WithSuggestField - specify which field to use for suggestions. -// -func (f Search) WithSuggestField(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.SuggestField = v - } -} - -// WithSuggestMode - specify suggest mode. -// -func (f Search) WithSuggestMode(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.SuggestMode = v - } -} - -// WithSuggestSize - how many suggestions to return in response. -// -func (f Search) WithSuggestSize(v int) func(*SearchRequest) { - return func(r *SearchRequest) { - r.SuggestSize = &v - } -} - -// WithSuggestText - the source text for which the suggestions should be returned. -// -func (f Search) WithSuggestText(v string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.SuggestText = v - } -} - -// WithTerminateAfter - the maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early.. -// -func (f Search) WithTerminateAfter(v int) func(*SearchRequest) { - return func(r *SearchRequest) { - r.TerminateAfter = &v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f Search) WithTimeout(v time.Duration) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Timeout = v - } -} - -// WithTrackScores - whether to calculate and return scores even if they are not used for sorting. -// -func (f Search) WithTrackScores(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.TrackScores = &v - } -} - -// WithTrackTotalHits - indicate if the number of documents that match the query should be tracked. -// -func (f Search) WithTrackTotalHits(v interface{}) func(*SearchRequest) { - return func(r *SearchRequest) { - r.TrackTotalHits = v - } -} - -// WithTypedKeys - specify whether aggregation and suggester names should be prefixed by their respective types in the response. -// -func (f Search) WithTypedKeys(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.TypedKeys = &v - } -} - -// WithVersion - specify whether to return document version as part of a hit. -// -func (f Search) WithVersion(v bool) func(*SearchRequest) { - return func(r *SearchRequest) { - r.Version = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Search) WithPretty() func(*SearchRequest) { - return func(r *SearchRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Search) WithHuman() func(*SearchRequest) { - return func(r *SearchRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Search) WithErrorTrace() func(*SearchRequest) { - return func(r *SearchRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Search) WithFilterPath(v ...string) func(*SearchRequest) { - return func(r *SearchRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Search) WithHeader(h map[string]string) func(*SearchRequest) { - return func(r *SearchRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Search) WithOpaqueID(s string) func(*SearchRequest) { - return func(r *SearchRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.search_shards.go b/opensearchapi/api.search_shards.go deleted file mode 100644 index 2e8bc30a0..000000000 --- a/opensearchapi/api.search_shards.go +++ /dev/null @@ -1,297 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newSearchShardsFunc(t Transport) SearchShards { - return func(o ...func(*SearchShardsRequest)) (*Response, error) { - var r = SearchShardsRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SearchShards returns information about the indices and shards that a search request would be executed against. -// -// -type SearchShards func(o ...func(*SearchShardsRequest)) (*Response, error) - -// SearchShardsRequest configures the Search Shards API request. -// -type SearchShardsRequest struct { - Index []string - - AllowNoIndices *bool - ExpandWildcards string - IgnoreUnavailable *bool - Local *bool - Preference string - Routing string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SearchShardsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_search_shards")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_search_shards") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SearchShards) WithContext(v context.Context) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to search; use _all to perform the operation on all indices. -// -func (f SearchShards) WithIndex(v ...string) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f SearchShards) WithAllowNoIndices(v bool) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.AllowNoIndices = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f SearchShards) WithExpandWildcards(v string) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.ExpandWildcards = v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f SearchShards) WithIgnoreUnavailable(v bool) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f SearchShards) WithLocal(v bool) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.Local = &v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f SearchShards) WithPreference(v string) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.Preference = v - } -} - -// WithRouting - specific routing value. -// -func (f SearchShards) WithRouting(v string) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.Routing = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SearchShards) WithPretty() func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SearchShards) WithHuman() func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SearchShards) WithErrorTrace() func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SearchShards) WithFilterPath(v ...string) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SearchShards) WithHeader(h map[string]string) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SearchShards) WithOpaqueID(s string) func(*SearchShardsRequest) { - return func(r *SearchShardsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.search_template.go b/opensearchapi/api.search_template.go deleted file mode 100644 index 376950b8f..000000000 --- a/opensearchapi/api.search_template.go +++ /dev/null @@ -1,398 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newSearchTemplateFunc(t Transport) SearchTemplate { - return func(body io.Reader, o ...func(*SearchTemplateRequest)) (*Response, error) { - var r = SearchTemplateRequest{Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SearchTemplate allows to use the Mustache language to pre-render a search definition. -// -// -type SearchTemplate func(body io.Reader, o ...func(*SearchTemplateRequest)) (*Response, error) - -// SearchTemplateRequest configures the Search Template API request. -// -type SearchTemplateRequest struct { - Index []string - - Body io.Reader - - AllowNoIndices *bool - CcsMinimizeRoundtrips *bool - ExpandWildcards string - Explain *bool - IgnoreThrottled *bool - IgnoreUnavailable *bool - Preference string - Profile *bool - RestTotalHitsAsInt *bool - Routing []string - Scroll time.Duration - SearchType string - TypedKeys *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SearchTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_search") + 1 + len("template")) - if len(r.Index) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - } - path.WriteString("/") - path.WriteString("_search") - path.WriteString("/") - path.WriteString("template") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.CcsMinimizeRoundtrips != nil { - params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.Explain != nil { - params["explain"] = strconv.FormatBool(*r.Explain) - } - - if r.IgnoreThrottled != nil { - params["ignore_throttled"] = strconv.FormatBool(*r.IgnoreThrottled) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Profile != nil { - params["profile"] = strconv.FormatBool(*r.Profile) - } - - if r.RestTotalHitsAsInt != nil { - params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) - } - - if len(r.Routing) > 0 { - params["routing"] = strings.Join(r.Routing, ",") - } - - if r.Scroll != 0 { - params["scroll"] = formatDuration(r.Scroll) - } - - if r.SearchType != "" { - params["search_type"] = r.SearchType - } - - if r.TypedKeys != nil { - params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SearchTemplate) WithContext(v context.Context) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.ctx = v - } -} - -// WithIndex - a list of index names to search; use _all to perform the operation on all indices. -// -func (f SearchTemplate) WithIndex(v ...string) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.Index = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f SearchTemplate) WithAllowNoIndices(v bool) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.AllowNoIndices = &v - } -} - -// WithCcsMinimizeRoundtrips - indicates whether network round-trips should be minimized as part of cross-cluster search requests execution. -// -func (f SearchTemplate) WithCcsMinimizeRoundtrips(v bool) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.CcsMinimizeRoundtrips = &v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f SearchTemplate) WithExpandWildcards(v string) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.ExpandWildcards = v - } -} - -// WithExplain - specify whether to return detailed information about score computation as part of a hit. -// -func (f SearchTemplate) WithExplain(v bool) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.Explain = &v - } -} - -// WithIgnoreThrottled - whether specified concrete, expanded or aliased indices should be ignored when throttled. -// -func (f SearchTemplate) WithIgnoreThrottled(v bool) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.IgnoreThrottled = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f SearchTemplate) WithIgnoreUnavailable(v bool) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f SearchTemplate) WithPreference(v string) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.Preference = v - } -} - -// WithProfile - specify whether to profile the query execution. -// -func (f SearchTemplate) WithProfile(v bool) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.Profile = &v - } -} - -// WithRestTotalHitsAsInt - indicates whether hits.total should be rendered as an integer or an object in the rest search response. -// -func (f SearchTemplate) WithRestTotalHitsAsInt(v bool) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.RestTotalHitsAsInt = &v - } -} - -// WithRouting - a list of specific routing values. -// -func (f SearchTemplate) WithRouting(v ...string) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.Routing = v - } -} - -// WithScroll - specify how long a consistent view of the index should be maintained for scrolled search. -// -func (f SearchTemplate) WithScroll(v time.Duration) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.Scroll = v - } -} - -// WithSearchType - search operation type. -// -func (f SearchTemplate) WithSearchType(v string) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.SearchType = v - } -} - -// WithTypedKeys - specify whether aggregation and suggester names should be prefixed by their respective types in the response. -// -func (f SearchTemplate) WithTypedKeys(v bool) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.TypedKeys = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SearchTemplate) WithPretty() func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SearchTemplate) WithHuman() func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SearchTemplate) WithErrorTrace() func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SearchTemplate) WithFilterPath(v ...string) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SearchTemplate) WithHeader(h map[string]string) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SearchTemplate) WithOpaqueID(s string) func(*SearchTemplateRequest) { - return func(r *SearchTemplateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.cleanup_repository.go b/opensearchapi/api.snapshot.cleanup_repository.go deleted file mode 100644 index 319c15276..000000000 --- a/opensearchapi/api.snapshot.cleanup_repository.go +++ /dev/null @@ -1,252 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newSnapshotCleanupRepositoryFunc(t Transport) SnapshotCleanupRepository { - return func(repository string, o ...func(*SnapshotCleanupRepositoryRequest)) (*Response, error) { - var r = SnapshotCleanupRepositoryRequest{Repository: repository} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotCleanupRepository removes stale data from repository. -// -// -type SnapshotCleanupRepository func(repository string, o ...func(*SnapshotCleanupRepositoryRequest)) (*Response, error) - -// SnapshotCleanupRepositoryRequest configures the Snapshot Cleanup Repository API request. -// -type SnapshotCleanupRepositoryRequest struct { - Repository string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotCleanupRepositoryRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_snapshot") + 1 + len(r.Repository) + 1 + len("_cleanup")) - path.WriteString("/") - path.WriteString("_snapshot") - path.WriteString("/") - path.WriteString(r.Repository) - path.WriteString("/") - path.WriteString("_cleanup") - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotCleanupRepository) WithContext(v context.Context) func(*SnapshotCleanupRepositoryRequest) { - return func(r *SnapshotCleanupRepositoryRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotCleanupRepository) WithMasterTimeout(v time.Duration) func(*SnapshotCleanupRepositoryRequest) { - return func(r *SnapshotCleanupRepositoryRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotCleanupRepository) WithClusterManagerTimeout(v time.Duration) func(*SnapshotCleanupRepositoryRequest) { - return func(r *SnapshotCleanupRepositoryRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f SnapshotCleanupRepository) WithTimeout(v time.Duration) func(*SnapshotCleanupRepositoryRequest) { - return func(r *SnapshotCleanupRepositoryRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotCleanupRepository) WithPretty() func(*SnapshotCleanupRepositoryRequest) { - return func(r *SnapshotCleanupRepositoryRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotCleanupRepository) WithHuman() func(*SnapshotCleanupRepositoryRequest) { - return func(r *SnapshotCleanupRepositoryRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotCleanupRepository) WithErrorTrace() func(*SnapshotCleanupRepositoryRequest) { - return func(r *SnapshotCleanupRepositoryRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotCleanupRepository) WithFilterPath(v ...string) func(*SnapshotCleanupRepositoryRequest) { - return func(r *SnapshotCleanupRepositoryRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotCleanupRepository) WithHeader(h map[string]string) func(*SnapshotCleanupRepositoryRequest) { - return func(r *SnapshotCleanupRepositoryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotCleanupRepository) WithOpaqueID(s string) func(*SnapshotCleanupRepositoryRequest) { - return func(r *SnapshotCleanupRepositoryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.clone.go b/opensearchapi/api.snapshot.clone.go deleted file mode 100644 index a8ade0c18..000000000 --- a/opensearchapi/api.snapshot.clone.go +++ /dev/null @@ -1,252 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" - "time" -) - -func newSnapshotCloneFunc(t Transport) SnapshotClone { - return func(repository string, snapshot string, body io.Reader, target_snapshot string, o ...func(*SnapshotCloneRequest)) (*Response, error) { - var r = SnapshotCloneRequest{Repository: repository, Snapshot: snapshot, Body: body, TargetSnapshot: target_snapshot} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotClone clones indices from one snapshot into another snapshot in the same repository. -// -// -type SnapshotClone func(repository string, snapshot string, body io.Reader, target_snapshot string, o ...func(*SnapshotCloneRequest)) (*Response, error) - -// SnapshotCloneRequest configures the Snapshot Clone API request. -// -type SnapshotCloneRequest struct { - Body io.Reader - - Repository string - Snapshot string - TargetSnapshot string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotCloneRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len("_snapshot") + 1 + len(r.Repository) + 1 + len(r.Snapshot) + 1 + len("_clone") + 1 + len(r.TargetSnapshot)) - path.WriteString("/") - path.WriteString("_snapshot") - path.WriteString("/") - path.WriteString(r.Repository) - path.WriteString("/") - path.WriteString(r.Snapshot) - path.WriteString("/") - path.WriteString("_clone") - path.WriteString("/") - path.WriteString(r.TargetSnapshot) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotClone) WithContext(v context.Context) func(*SnapshotCloneRequest) { - return func(r *SnapshotCloneRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotClone) WithMasterTimeout(v time.Duration) func(*SnapshotCloneRequest) { - return func(r *SnapshotCloneRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotClone) WithClusterManagerTimeout(v time.Duration) func(*SnapshotCloneRequest) { - return func(r *SnapshotCloneRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotClone) WithPretty() func(*SnapshotCloneRequest) { - return func(r *SnapshotCloneRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotClone) WithHuman() func(*SnapshotCloneRequest) { - return func(r *SnapshotCloneRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotClone) WithErrorTrace() func(*SnapshotCloneRequest) { - return func(r *SnapshotCloneRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotClone) WithFilterPath(v ...string) func(*SnapshotCloneRequest) { - return func(r *SnapshotCloneRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotClone) WithHeader(h map[string]string) func(*SnapshotCloneRequest) { - return func(r *SnapshotCloneRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotClone) WithOpaqueID(s string) func(*SnapshotCloneRequest) { - return func(r *SnapshotCloneRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.create.go b/opensearchapi/api.snapshot.create.go deleted file mode 100644 index b29a9dd55..000000000 --- a/opensearchapi/api.snapshot.create.go +++ /dev/null @@ -1,269 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newSnapshotCreateFunc(t Transport) SnapshotCreate { - return func(repository string, snapshot string, o ...func(*SnapshotCreateRequest)) (*Response, error) { - var r = SnapshotCreateRequest{Repository: repository, Snapshot: snapshot} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotCreate creates a snapshot in a repository. -// -// -type SnapshotCreate func(repository string, snapshot string, o ...func(*SnapshotCreateRequest)) (*Response, error) - -// SnapshotCreateRequest configures the Snapshot Create API request. -// -type SnapshotCreateRequest struct { - Body io.Reader - - Repository string - Snapshot string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - WaitForCompletion *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotCreateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len("_snapshot") + 1 + len(r.Repository) + 1 + len(r.Snapshot)) - path.WriteString("/") - path.WriteString("_snapshot") - path.WriteString("/") - path.WriteString(r.Repository) - path.WriteString("/") - path.WriteString(r.Snapshot) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.WaitForCompletion != nil { - params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotCreate) WithContext(v context.Context) func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - r.ctx = v - } -} - -// WithBody - The snapshot definition. -// -func (f SnapshotCreate) WithBody(v io.Reader) func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - r.Body = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotCreate) WithMasterTimeout(v time.Duration) func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotCreate) WithClusterManagerTimeout(v time.Duration) func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithWaitForCompletion - should this request wait until the operation has completed before returning. -// -func (f SnapshotCreate) WithWaitForCompletion(v bool) func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - r.WaitForCompletion = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotCreate) WithPretty() func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotCreate) WithHuman() func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotCreate) WithErrorTrace() func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotCreate) WithFilterPath(v ...string) func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotCreate) WithHeader(h map[string]string) func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotCreate) WithOpaqueID(s string) func(*SnapshotCreateRequest) { - return func(r *SnapshotCreateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.create_repository.go b/opensearchapi/api.snapshot.create_repository.go deleted file mode 100644 index ab2a1169a..000000000 --- a/opensearchapi/api.snapshot.create_repository.go +++ /dev/null @@ -1,271 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newSnapshotCreateRepositoryFunc(t Transport) SnapshotCreateRepository { - return func(repository string, body io.Reader, o ...func(*SnapshotCreateRepositoryRequest)) (*Response, error) { - var r = SnapshotCreateRepositoryRequest{Repository: repository, Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotCreateRepository creates a repository. -// -// -type SnapshotCreateRepository func(repository string, body io.Reader, o ...func(*SnapshotCreateRepositoryRequest)) (*Response, error) - -// SnapshotCreateRepositoryRequest configures the Snapshot Create Repository API request. -// -type SnapshotCreateRepositoryRequest struct { - Body io.Reader - - Repository string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - Verify *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotCreateRepositoryRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "PUT" - - path.Grow(1 + len("_snapshot") + 1 + len(r.Repository)) - path.WriteString("/") - path.WriteString("_snapshot") - path.WriteString("/") - path.WriteString(r.Repository) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Verify != nil { - params["verify"] = strconv.FormatBool(*r.Verify) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotCreateRepository) WithContext(v context.Context) func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotCreateRepository) WithMasterTimeout(v time.Duration) func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotCreateRepository) WithClusterManagerTimeout(v time.Duration) func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f SnapshotCreateRepository) WithTimeout(v time.Duration) func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - r.Timeout = v - } -} - -// WithVerify - whether to verify the repository after creation. -// -func (f SnapshotCreateRepository) WithVerify(v bool) func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - r.Verify = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotCreateRepository) WithPretty() func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotCreateRepository) WithHuman() func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotCreateRepository) WithErrorTrace() func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotCreateRepository) WithFilterPath(v ...string) func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotCreateRepository) WithHeader(h map[string]string) func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotCreateRepository) WithOpaqueID(s string) func(*SnapshotCreateRepositoryRequest) { - return func(r *SnapshotCreateRepositoryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.delete.go b/opensearchapi/api.snapshot.delete.go deleted file mode 100644 index 1d2021ad2..000000000 --- a/opensearchapi/api.snapshot.delete.go +++ /dev/null @@ -1,240 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newSnapshotDeleteFunc(t Transport) SnapshotDelete { - return func(repository string, snapshot []string, o ...func(*SnapshotDeleteRequest)) (*Response, error) { - var r = SnapshotDeleteRequest{Repository: repository, Snapshot: snapshot} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotDelete deletes a snapshot. -// -// -type SnapshotDelete func(repository string, snapshot []string, o ...func(*SnapshotDeleteRequest)) (*Response, error) - -// SnapshotDeleteRequest configures the Snapshot Delete API request. -// -type SnapshotDeleteRequest struct { - Repository string - Snapshot []string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotDeleteRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len("_snapshot") + 1 + len(r.Repository) + 1 + len(strings.Join(r.Snapshot, ","))) - path.WriteString("/") - path.WriteString("_snapshot") - path.WriteString("/") - path.WriteString(r.Repository) - path.WriteString("/") - path.WriteString(strings.Join(r.Snapshot, ",")) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotDelete) WithContext(v context.Context) func(*SnapshotDeleteRequest) { - return func(r *SnapshotDeleteRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotDelete) WithMasterTimeout(v time.Duration) func(*SnapshotDeleteRequest) { - return func(r *SnapshotDeleteRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotDelete) WithClusterManagerTimeout(v time.Duration) func(*SnapshotDeleteRequest) { - return func(r *SnapshotDeleteRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotDelete) WithPretty() func(*SnapshotDeleteRequest) { - return func(r *SnapshotDeleteRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotDelete) WithHuman() func(*SnapshotDeleteRequest) { - return func(r *SnapshotDeleteRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotDelete) WithErrorTrace() func(*SnapshotDeleteRequest) { - return func(r *SnapshotDeleteRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotDelete) WithFilterPath(v ...string) func(*SnapshotDeleteRequest) { - return func(r *SnapshotDeleteRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotDelete) WithHeader(h map[string]string) func(*SnapshotDeleteRequest) { - return func(r *SnapshotDeleteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotDelete) WithOpaqueID(s string) func(*SnapshotDeleteRequest) { - return func(r *SnapshotDeleteRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.delete_repository.go b/opensearchapi/api.snapshot.delete_repository.go deleted file mode 100644 index 7aaa3c743..000000000 --- a/opensearchapi/api.snapshot.delete_repository.go +++ /dev/null @@ -1,250 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newSnapshotDeleteRepositoryFunc(t Transport) SnapshotDeleteRepository { - return func(repository []string, o ...func(*SnapshotDeleteRepositoryRequest)) (*Response, error) { - var r = SnapshotDeleteRepositoryRequest{Repository: repository} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotDeleteRepository deletes a repository. -// -// -type SnapshotDeleteRepository func(repository []string, o ...func(*SnapshotDeleteRepositoryRequest)) (*Response, error) - -// SnapshotDeleteRepositoryRequest configures the Snapshot Delete Repository API request. -// -type SnapshotDeleteRepositoryRequest struct { - Repository []string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotDeleteRepositoryRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "DELETE" - - path.Grow(1 + len("_snapshot") + 1 + len(strings.Join(r.Repository, ","))) - path.WriteString("/") - path.WriteString("_snapshot") - path.WriteString("/") - path.WriteString(strings.Join(r.Repository, ",")) - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotDeleteRepository) WithContext(v context.Context) func(*SnapshotDeleteRepositoryRequest) { - return func(r *SnapshotDeleteRepositoryRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotDeleteRepository) WithMasterTimeout(v time.Duration) func(*SnapshotDeleteRepositoryRequest) { - return func(r *SnapshotDeleteRepositoryRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotDeleteRepository) WithClusterManagerTimeout(v time.Duration) func(*SnapshotDeleteRepositoryRequest) { - return func(r *SnapshotDeleteRepositoryRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f SnapshotDeleteRepository) WithTimeout(v time.Duration) func(*SnapshotDeleteRepositoryRequest) { - return func(r *SnapshotDeleteRepositoryRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotDeleteRepository) WithPretty() func(*SnapshotDeleteRepositoryRequest) { - return func(r *SnapshotDeleteRepositoryRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotDeleteRepository) WithHuman() func(*SnapshotDeleteRepositoryRequest) { - return func(r *SnapshotDeleteRepositoryRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotDeleteRepository) WithErrorTrace() func(*SnapshotDeleteRepositoryRequest) { - return func(r *SnapshotDeleteRepositoryRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotDeleteRepository) WithFilterPath(v ...string) func(*SnapshotDeleteRepositoryRequest) { - return func(r *SnapshotDeleteRepositoryRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotDeleteRepository) WithHeader(h map[string]string) func(*SnapshotDeleteRepositoryRequest) { - return func(r *SnapshotDeleteRepositoryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotDeleteRepository) WithOpaqueID(s string) func(*SnapshotDeleteRepositoryRequest) { - return func(r *SnapshotDeleteRepositoryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.get.go b/opensearchapi/api.snapshot.get.go deleted file mode 100644 index 8cdb685aa..000000000 --- a/opensearchapi/api.snapshot.get.go +++ /dev/null @@ -1,293 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newSnapshotGetFunc(t Transport) SnapshotGet { - return func(repository string, snapshot []string, o ...func(*SnapshotGetRequest)) (*Response, error) { - var r = SnapshotGetRequest{Repository: repository, Snapshot: snapshot} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotGet returns information about a snapshot. -// -// -type SnapshotGet func(repository string, snapshot []string, o ...func(*SnapshotGetRequest)) (*Response, error) - -// SnapshotGetRequest configures the Snapshot Get API request. -// -type SnapshotGetRequest struct { - Repository string - Snapshot []string - - IgnoreUnavailable *bool - IncludeRepository *bool - IndexDetails *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Verbose *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotGetRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_snapshot") + 1 + len(r.Repository) + 1 + len(strings.Join(r.Snapshot, ","))) - path.WriteString("/") - path.WriteString("_snapshot") - path.WriteString("/") - path.WriteString(r.Repository) - path.WriteString("/") - path.WriteString(strings.Join(r.Snapshot, ",")) - - params = make(map[string]string) - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.IncludeRepository != nil { - params["include_repository"] = strconv.FormatBool(*r.IncludeRepository) - } - - if r.IndexDetails != nil { - params["index_details"] = strconv.FormatBool(*r.IndexDetails) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Verbose != nil { - params["verbose"] = strconv.FormatBool(*r.Verbose) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotGet) WithContext(v context.Context) func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.ctx = v - } -} - -// WithIgnoreUnavailable - whether to ignore unavailable snapshots, defaults to false which means a snapshotmissingexception is thrown. -// -func (f SnapshotGet) WithIgnoreUnavailable(v bool) func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithIncludeRepository - whether to include the repository name in the snapshot info. defaults to true.. -// -func (f SnapshotGet) WithIncludeRepository(v bool) func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.IncludeRepository = &v - } -} - -// WithIndexDetails - whether to include details of each index in the snapshot, if those details are available. defaults to false.. -// -func (f SnapshotGet) WithIndexDetails(v bool) func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.IndexDetails = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotGet) WithMasterTimeout(v time.Duration) func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotGet) WithClusterManagerTimeout(v time.Duration) func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithVerbose - whether to show verbose snapshot info or only show the basic info found in the repository index blob. -// -func (f SnapshotGet) WithVerbose(v bool) func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.Verbose = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotGet) WithPretty() func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotGet) WithHuman() func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotGet) WithErrorTrace() func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotGet) WithFilterPath(v ...string) func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotGet) WithHeader(h map[string]string) func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotGet) WithOpaqueID(s string) func(*SnapshotGetRequest) { - return func(r *SnapshotGetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.get_repository.go b/opensearchapi/api.snapshot.get_repository.go deleted file mode 100644 index 0466a90d0..000000000 --- a/opensearchapi/api.snapshot.get_repository.go +++ /dev/null @@ -1,261 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newSnapshotGetRepositoryFunc(t Transport) SnapshotGetRepository { - return func(o ...func(*SnapshotGetRepositoryRequest)) (*Response, error) { - var r = SnapshotGetRepositoryRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotGetRepository returns information about a repository. -// -// -type SnapshotGetRepository func(o ...func(*SnapshotGetRepositoryRequest)) (*Response, error) - -// SnapshotGetRepositoryRequest configures the Snapshot Get Repository API request. -// -type SnapshotGetRepositoryRequest struct { - Repository []string - - Local *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotGetRepositoryRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_snapshot") + 1 + len(strings.Join(r.Repository, ","))) - path.WriteString("/") - path.WriteString("_snapshot") - if len(r.Repository) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Repository, ",")) - } - - params = make(map[string]string) - - if r.Local != nil { - params["local"] = strconv.FormatBool(*r.Local) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotGetRepository) WithContext(v context.Context) func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - r.ctx = v - } -} - -// WithRepository - a list of repository names. -// -func (f SnapshotGetRepository) WithRepository(v ...string) func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - r.Repository = v - } -} - -// WithLocal - return local information, do not retrieve the state from cluster-manager node (default: false). -// -func (f SnapshotGetRepository) WithLocal(v bool) func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - r.Local = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotGetRepository) WithMasterTimeout(v time.Duration) func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotGetRepository) WithClusterManagerTimeout(v time.Duration) func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotGetRepository) WithPretty() func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotGetRepository) WithHuman() func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotGetRepository) WithErrorTrace() func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotGetRepository) WithFilterPath(v ...string) func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotGetRepository) WithHeader(h map[string]string) func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotGetRepository) WithOpaqueID(s string) func(*SnapshotGetRepositoryRequest) { - return func(r *SnapshotGetRepositoryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.restore.go b/opensearchapi/api.snapshot.restore.go deleted file mode 100644 index 46eb158b9..000000000 --- a/opensearchapi/api.snapshot.restore.go +++ /dev/null @@ -1,271 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newSnapshotRestoreFunc(t Transport) SnapshotRestore { - return func(repository string, snapshot string, o ...func(*SnapshotRestoreRequest)) (*Response, error) { - var r = SnapshotRestoreRequest{Repository: repository, Snapshot: snapshot} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotRestore restores a snapshot. -// -// -type SnapshotRestore func(repository string, snapshot string, o ...func(*SnapshotRestoreRequest)) (*Response, error) - -// SnapshotRestoreRequest configures the Snapshot Restore API request. -// -type SnapshotRestoreRequest struct { - Body io.Reader - - Repository string - Snapshot string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - WaitForCompletion *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotRestoreRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_snapshot") + 1 + len(r.Repository) + 1 + len(r.Snapshot) + 1 + len("_restore")) - path.WriteString("/") - path.WriteString("_snapshot") - path.WriteString("/") - path.WriteString(r.Repository) - path.WriteString("/") - path.WriteString(r.Snapshot) - path.WriteString("/") - path.WriteString("_restore") - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.WaitForCompletion != nil { - params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotRestore) WithContext(v context.Context) func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - r.ctx = v - } -} - -// WithBody - Details of what to restore. -// -func (f SnapshotRestore) WithBody(v io.Reader) func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - r.Body = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotRestore) WithMasterTimeout(v time.Duration) func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotRestore) WithClusterManagerTimeout(v time.Duration) func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithWaitForCompletion - should this request wait until the operation has completed before returning. -// -func (f SnapshotRestore) WithWaitForCompletion(v bool) func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - r.WaitForCompletion = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotRestore) WithPretty() func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotRestore) WithHuman() func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotRestore) WithErrorTrace() func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotRestore) WithFilterPath(v ...string) func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotRestore) WithHeader(h map[string]string) func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotRestore) WithOpaqueID(s string) func(*SnapshotRestoreRequest) { - return func(r *SnapshotRestoreRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.status.go b/opensearchapi/api.snapshot.status.go deleted file mode 100644 index ee3be0ed6..000000000 --- a/opensearchapi/api.snapshot.status.go +++ /dev/null @@ -1,276 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newSnapshotStatusFunc(t Transport) SnapshotStatus { - return func(o ...func(*SnapshotStatusRequest)) (*Response, error) { - var r = SnapshotStatusRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotStatus returns information about the status of a snapshot. -// -// -type SnapshotStatus func(o ...func(*SnapshotStatusRequest)) (*Response, error) - -// SnapshotStatusRequest configures the Snapshot Status API request. -// -type SnapshotStatusRequest struct { - Repository string - Snapshot []string - - IgnoreUnavailable *bool - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotStatusRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_snapshot") + 1 + len(r.Repository) + 1 + len(strings.Join(r.Snapshot, ",")) + 1 + len("_status")) - path.WriteString("/") - path.WriteString("_snapshot") - if r.Repository != "" { - path.WriteString("/") - path.WriteString(r.Repository) - } - if len(r.Snapshot) > 0 { - path.WriteString("/") - path.WriteString(strings.Join(r.Snapshot, ",")) - } - path.WriteString("/") - path.WriteString("_status") - - params = make(map[string]string) - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotStatus) WithContext(v context.Context) func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - r.ctx = v - } -} - -// WithRepository - a repository name. -// -func (f SnapshotStatus) WithRepository(v string) func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - r.Repository = v - } -} - -// WithSnapshot - a list of snapshot names. -// -func (f SnapshotStatus) WithSnapshot(v ...string) func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - r.Snapshot = v - } -} - -// WithIgnoreUnavailable - whether to ignore unavailable snapshots, defaults to false which means a snapshotmissingexception is thrown. -// -func (f SnapshotStatus) WithIgnoreUnavailable(v bool) func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotStatus) WithMasterTimeout(v time.Duration) func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotStatus) WithClusterManagerTimeout(v time.Duration) func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotStatus) WithPretty() func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotStatus) WithHuman() func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotStatus) WithErrorTrace() func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotStatus) WithFilterPath(v ...string) func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotStatus) WithHeader(h map[string]string) func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotStatus) WithOpaqueID(s string) func(*SnapshotStatusRequest) { - return func(r *SnapshotStatusRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.snapshot.verify_repository.go b/opensearchapi/api.snapshot.verify_repository.go deleted file mode 100644 index 0d37d250e..000000000 --- a/opensearchapi/api.snapshot.verify_repository.go +++ /dev/null @@ -1,252 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strings" - "time" -) - -func newSnapshotVerifyRepositoryFunc(t Transport) SnapshotVerifyRepository { - return func(repository string, o ...func(*SnapshotVerifyRepositoryRequest)) (*Response, error) { - var r = SnapshotVerifyRepositoryRequest{Repository: repository} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// SnapshotVerifyRepository verifies a repository. -// -// -type SnapshotVerifyRepository func(repository string, o ...func(*SnapshotVerifyRepositoryRequest)) (*Response, error) - -// SnapshotVerifyRepositoryRequest configures the Snapshot Verify Repository API request. -// -type SnapshotVerifyRepositoryRequest struct { - Repository string - - MasterTimeout time.Duration - ClusterManagerTimeout time.Duration - Timeout time.Duration - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r SnapshotVerifyRepositoryRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_snapshot") + 1 + len(r.Repository) + 1 + len("_verify")) - path.WriteString("/") - path.WriteString("_snapshot") - path.WriteString("/") - path.WriteString(r.Repository) - path.WriteString("/") - path.WriteString("_verify") - - params = make(map[string]string) - - if r.MasterTimeout != 0 { - params["master_timeout"] = formatDuration(r.MasterTimeout) - } - - if r.ClusterManagerTimeout != 0 { - params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f SnapshotVerifyRepository) WithContext(v context.Context) func(*SnapshotVerifyRepositoryRequest) { - return func(r *SnapshotVerifyRepositoryRequest) { - r.ctx = v - } -} - -// WithMasterTimeout - explicit operation timeout for connection to cluster-manager node. -// -// Deprecated: To promote inclusive language, use WithClusterManagerTimeout instead. -// -func (f SnapshotVerifyRepository) WithMasterTimeout(v time.Duration) func(*SnapshotVerifyRepositoryRequest) { - return func(r *SnapshotVerifyRepositoryRequest) { - r.MasterTimeout = v - } -} - -// WithClusterManagerTimeout - explicit operation timeout for connection to cluster-manager node. -// -func (f SnapshotVerifyRepository) WithClusterManagerTimeout(v time.Duration) func(*SnapshotVerifyRepositoryRequest) { - return func(r *SnapshotVerifyRepositoryRequest) { - r.ClusterManagerTimeout = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f SnapshotVerifyRepository) WithTimeout(v time.Duration) func(*SnapshotVerifyRepositoryRequest) { - return func(r *SnapshotVerifyRepositoryRequest) { - r.Timeout = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f SnapshotVerifyRepository) WithPretty() func(*SnapshotVerifyRepositoryRequest) { - return func(r *SnapshotVerifyRepositoryRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f SnapshotVerifyRepository) WithHuman() func(*SnapshotVerifyRepositoryRequest) { - return func(r *SnapshotVerifyRepositoryRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f SnapshotVerifyRepository) WithErrorTrace() func(*SnapshotVerifyRepositoryRequest) { - return func(r *SnapshotVerifyRepositoryRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f SnapshotVerifyRepository) WithFilterPath(v ...string) func(*SnapshotVerifyRepositoryRequest) { - return func(r *SnapshotVerifyRepositoryRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f SnapshotVerifyRepository) WithHeader(h map[string]string) func(*SnapshotVerifyRepositoryRequest) { - return func(r *SnapshotVerifyRepositoryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f SnapshotVerifyRepository) WithOpaqueID(s string) func(*SnapshotVerifyRepositoryRequest) { - return func(r *SnapshotVerifyRepositoryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.tasks.cancel.go b/opensearchapi/api.tasks.cancel.go deleted file mode 100644 index 700724926..000000000 --- a/opensearchapi/api.tasks.cancel.go +++ /dev/null @@ -1,275 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newTasksCancelFunc(t Transport) TasksCancel { - return func(o ...func(*TasksCancelRequest)) (*Response, error) { - var r = TasksCancelRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// TasksCancel cancels a task, if it can be cancelled through an API. -// -// This API is experimental. -// -// -type TasksCancel func(o ...func(*TasksCancelRequest)) (*Response, error) - -// TasksCancelRequest configures the Tasks Cancel API request. -// -type TasksCancelRequest struct { - TaskID string - - Actions []string - Nodes []string - ParentTaskID string - WaitForCompletion *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r TasksCancelRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_tasks") + 1 + len(r.TaskID) + 1 + len("_cancel")) - path.WriteString("/") - path.WriteString("_tasks") - if r.TaskID != "" { - path.WriteString("/") - path.WriteString(r.TaskID) - } - path.WriteString("/") - path.WriteString("_cancel") - - params = make(map[string]string) - - if len(r.Actions) > 0 { - params["actions"] = strings.Join(r.Actions, ",") - } - - if len(r.Nodes) > 0 { - params["nodes"] = strings.Join(r.Nodes, ",") - } - - if r.ParentTaskID != "" { - params["parent_task_id"] = r.ParentTaskID - } - - if r.WaitForCompletion != nil { - params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f TasksCancel) WithContext(v context.Context) func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - r.ctx = v - } -} - -// WithTaskID - cancel the task with specified task ID (node_id:task_number). -// -func (f TasksCancel) WithTaskID(v string) func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - r.TaskID = v - } -} - -// WithActions - a list of actions that should be cancelled. leave empty to cancel all.. -// -func (f TasksCancel) WithActions(v ...string) func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - r.Actions = v - } -} - -// WithNodes - a list of node ids or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes. -// -func (f TasksCancel) WithNodes(v ...string) func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - r.Nodes = v - } -} - -// WithParentTaskID - cancel tasks with specified parent task ID (node_id:task_number). set to -1 to cancel all.. -// -func (f TasksCancel) WithParentTaskID(v string) func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - r.ParentTaskID = v - } -} - -// WithWaitForCompletion - should the request block until the cancellation of the task and its descendant tasks is completed. defaults to false. -// -func (f TasksCancel) WithWaitForCompletion(v bool) func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - r.WaitForCompletion = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f TasksCancel) WithPretty() func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f TasksCancel) WithHuman() func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f TasksCancel) WithErrorTrace() func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f TasksCancel) WithFilterPath(v ...string) func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f TasksCancel) WithHeader(h map[string]string) func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f TasksCancel) WithOpaqueID(s string) func(*TasksCancelRequest) { - return func(r *TasksCancelRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.tasks.get.go b/opensearchapi/api.tasks.get.go deleted file mode 100644 index e415b22b4..000000000 --- a/opensearchapi/api.tasks.get.go +++ /dev/null @@ -1,238 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newTasksGetFunc(t Transport) TasksGet { - return func(task_id string, o ...func(*TasksGetRequest)) (*Response, error) { - var r = TasksGetRequest{TaskID: task_id} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// TasksGet returns information about a task. -// -// This API is experimental. -// -// -type TasksGet func(task_id string, o ...func(*TasksGetRequest)) (*Response, error) - -// TasksGetRequest configures the Tasks Get API request. -// -type TasksGetRequest struct { - TaskID string - - Timeout time.Duration - WaitForCompletion *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r TasksGetRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(1 + len("_tasks") + 1 + len(r.TaskID)) - path.WriteString("/") - path.WriteString("_tasks") - path.WriteString("/") - path.WriteString(r.TaskID) - - params = make(map[string]string) - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForCompletion != nil { - params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f TasksGet) WithContext(v context.Context) func(*TasksGetRequest) { - return func(r *TasksGetRequest) { - r.ctx = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f TasksGet) WithTimeout(v time.Duration) func(*TasksGetRequest) { - return func(r *TasksGetRequest) { - r.Timeout = v - } -} - -// WithWaitForCompletion - wait for the matching tasks to complete (default: false). -// -func (f TasksGet) WithWaitForCompletion(v bool) func(*TasksGetRequest) { - return func(r *TasksGetRequest) { - r.WaitForCompletion = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f TasksGet) WithPretty() func(*TasksGetRequest) { - return func(r *TasksGetRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f TasksGet) WithHuman() func(*TasksGetRequest) { - return func(r *TasksGetRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f TasksGet) WithErrorTrace() func(*TasksGetRequest) { - return func(r *TasksGetRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f TasksGet) WithFilterPath(v ...string) func(*TasksGetRequest) { - return func(r *TasksGetRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f TasksGet) WithHeader(h map[string]string) func(*TasksGetRequest) { - return func(r *TasksGetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f TasksGet) WithOpaqueID(s string) func(*TasksGetRequest) { - return func(r *TasksGetRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.tasks.list.go b/opensearchapi/api.tasks.list.go deleted file mode 100644 index 061aea750..000000000 --- a/opensearchapi/api.tasks.list.go +++ /dev/null @@ -1,298 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" - "time" -) - -func newTasksListFunc(t Transport) TasksList { - return func(o ...func(*TasksListRequest)) (*Response, error) { - var r = TasksListRequest{} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// TasksList returns a list of tasks. -// -// This API is experimental. -// -// -type TasksList func(o ...func(*TasksListRequest)) (*Response, error) - -// TasksListRequest configures the Tasks List API request. -// -type TasksListRequest struct { - Actions []string - Detailed *bool - GroupBy string - Nodes []string - ParentTaskID string - Timeout time.Duration - WaitForCompletion *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r TasksListRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "GET" - - path.Grow(len("/_tasks")) - path.WriteString("/_tasks") - - params = make(map[string]string) - - if len(r.Actions) > 0 { - params["actions"] = strings.Join(r.Actions, ",") - } - - if r.Detailed != nil { - params["detailed"] = strconv.FormatBool(*r.Detailed) - } - - if r.GroupBy != "" { - params["group_by"] = r.GroupBy - } - - if len(r.Nodes) > 0 { - params["nodes"] = strings.Join(r.Nodes, ",") - } - - if r.ParentTaskID != "" { - params["parent_task_id"] = r.ParentTaskID - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForCompletion != nil { - params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f TasksList) WithContext(v context.Context) func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.ctx = v - } -} - -// WithActions - a list of actions that should be returned. leave empty to return all.. -// -func (f TasksList) WithActions(v ...string) func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.Actions = v - } -} - -// WithDetailed - return detailed task information (default: false). -// -func (f TasksList) WithDetailed(v bool) func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.Detailed = &v - } -} - -// WithGroupBy - group tasks by nodes or parent/child relationships. -// -func (f TasksList) WithGroupBy(v string) func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.GroupBy = v - } -} - -// WithNodes - a list of node ids or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes. -// -func (f TasksList) WithNodes(v ...string) func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.Nodes = v - } -} - -// WithParentTaskID - return tasks with specified parent task ID (node_id:task_number). set to -1 to return all.. -// -func (f TasksList) WithParentTaskID(v string) func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.ParentTaskID = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f TasksList) WithTimeout(v time.Duration) func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.Timeout = v - } -} - -// WithWaitForCompletion - wait for the matching tasks to complete (default: false). -// -func (f TasksList) WithWaitForCompletion(v bool) func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.WaitForCompletion = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f TasksList) WithPretty() func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f TasksList) WithHuman() func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f TasksList) WithErrorTrace() func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f TasksList) WithFilterPath(v ...string) func(*TasksListRequest) { - return func(r *TasksListRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f TasksList) WithHeader(h map[string]string) func(*TasksListRequest) { - return func(r *TasksListRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f TasksList) WithOpaqueID(s string) func(*TasksListRequest) { - return func(r *TasksListRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.terms_enum.go b/opensearchapi/api.terms_enum.go deleted file mode 100644 index 83735ac14..000000000 --- a/opensearchapi/api.terms_enum.go +++ /dev/null @@ -1,224 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strings" -) - -func newTermsEnumFunc(t Transport) TermsEnum { - return func(index []string, o ...func(*TermsEnumRequest)) (*Response, error) { - var r = TermsEnumRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// TermsEnum the terms enum API can be used to discover terms in the index that begin with the provided string. It is designed for low-latency look-ups used in auto-complete scenarios. -// -// This API is beta. -// -// -type TermsEnum func(index []string, o ...func(*TermsEnumRequest)) (*Response, error) - -// TermsEnumRequest configures the Terms Enum API request. -// -type TermsEnumRequest struct { - Index []string - - Body io.Reader - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r TermsEnumRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_terms_enum")) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - path.WriteString("/") - path.WriteString("_terms_enum") - - params = make(map[string]string) - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f TermsEnum) WithContext(v context.Context) func(*TermsEnumRequest) { - return func(r *TermsEnumRequest) { - r.ctx = v - } -} - -// WithBody - field name, string which is the prefix expected in matching terms, timeout and size for max number of results. -// -func (f TermsEnum) WithBody(v io.Reader) func(*TermsEnumRequest) { - return func(r *TermsEnumRequest) { - r.Body = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f TermsEnum) WithPretty() func(*TermsEnumRequest) { - return func(r *TermsEnumRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f TermsEnum) WithHuman() func(*TermsEnumRequest) { - return func(r *TermsEnumRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f TermsEnum) WithErrorTrace() func(*TermsEnumRequest) { - return func(r *TermsEnumRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f TermsEnum) WithFilterPath(v ...string) func(*TermsEnumRequest) { - return func(r *TermsEnumRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f TermsEnum) WithHeader(h map[string]string) func(*TermsEnumRequest) { - return func(r *TermsEnumRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f TermsEnum) WithOpaqueID(s string) func(*TermsEnumRequest) { - return func(r *TermsEnumRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.termvectors.go b/opensearchapi/api.termvectors.go deleted file mode 100644 index d67088026..000000000 --- a/opensearchapi/api.termvectors.go +++ /dev/null @@ -1,380 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" -) - -func newTermvectorsFunc(t Transport) Termvectors { - return func(index string, o ...func(*TermvectorsRequest)) (*Response, error) { - var r = TermvectorsRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Termvectors returns information and statistics about terms in the fields of a particular document. -// -// -type Termvectors func(index string, o ...func(*TermvectorsRequest)) (*Response, error) - -// TermvectorsRequest configures the Termvectors API request. -// -type TermvectorsRequest struct { - Index string - DocumentID string - - Body io.Reader - - Fields []string - FieldStatistics *bool - Offsets *bool - Payloads *bool - Positions *bool - Preference string - Realtime *bool - Routing string - TermStatistics *bool - Version *int - VersionType string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r TermvectorsRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(r.Index) + 1 + len(r.DocumentID) + 1 + len("_termvectors")) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_termvectors") - if r.DocumentID != "" { - path.WriteString("/") - path.WriteString(r.DocumentID) - } - - params = make(map[string]string) - - if len(r.Fields) > 0 { - params["fields"] = strings.Join(r.Fields, ",") - } - - if r.FieldStatistics != nil { - params["field_statistics"] = strconv.FormatBool(*r.FieldStatistics) - } - - if r.Offsets != nil { - params["offsets"] = strconv.FormatBool(*r.Offsets) - } - - if r.Payloads != nil { - params["payloads"] = strconv.FormatBool(*r.Payloads) - } - - if r.Positions != nil { - params["positions"] = strconv.FormatBool(*r.Positions) - } - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Realtime != nil { - params["realtime"] = strconv.FormatBool(*r.Realtime) - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if r.TermStatistics != nil { - params["term_statistics"] = strconv.FormatBool(*r.TermStatistics) - } - - if r.Version != nil { - params["version"] = strconv.FormatInt(int64(*r.Version), 10) - } - - if r.VersionType != "" { - params["version_type"] = r.VersionType - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Termvectors) WithContext(v context.Context) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.ctx = v - } -} - -// WithBody - Define parameters and or supply a document to get termvectors for. See documentation.. -// -func (f Termvectors) WithBody(v io.Reader) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Body = v - } -} - -// WithDocumentID - the ID of the document, when not specified a doc param should be supplied.. -// -func (f Termvectors) WithDocumentID(v string) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.DocumentID = v - } -} - -// WithFields - a list of fields to return.. -// -func (f Termvectors) WithFields(v ...string) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Fields = v - } -} - -// WithFieldStatistics - specifies if document count, sum of document frequencies and sum of total term frequencies should be returned.. -// -func (f Termvectors) WithFieldStatistics(v bool) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.FieldStatistics = &v - } -} - -// WithOffsets - specifies if term offsets should be returned.. -// -func (f Termvectors) WithOffsets(v bool) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Offsets = &v - } -} - -// WithPayloads - specifies if term payloads should be returned.. -// -func (f Termvectors) WithPayloads(v bool) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Payloads = &v - } -} - -// WithPositions - specifies if term positions should be returned.. -// -func (f Termvectors) WithPositions(v bool) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Positions = &v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random).. -// -func (f Termvectors) WithPreference(v string) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Preference = v - } -} - -// WithRealtime - specifies if request is real-time as opposed to near-real-time (default: true).. -// -func (f Termvectors) WithRealtime(v bool) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Realtime = &v - } -} - -// WithRouting - specific routing value.. -// -func (f Termvectors) WithRouting(v string) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Routing = v - } -} - -// WithTermStatistics - specifies if total term frequency and document frequency should be returned.. -// -func (f Termvectors) WithTermStatistics(v bool) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.TermStatistics = &v - } -} - -// WithVersion - explicit version number for concurrency control. -// -func (f Termvectors) WithVersion(v int) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Version = &v - } -} - -// WithVersionType - specific version type. -// -func (f Termvectors) WithVersionType(v string) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.VersionType = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Termvectors) WithPretty() func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Termvectors) WithHuman() func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Termvectors) WithErrorTrace() func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Termvectors) WithFilterPath(v ...string) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Termvectors) WithHeader(h map[string]string) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Termvectors) WithOpaqueID(s string) func(*TermvectorsRequest) { - return func(r *TermvectorsRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.update.go b/opensearchapi/api.update.go deleted file mode 100644 index f17ea760f..000000000 --- a/opensearchapi/api.update.go +++ /dev/null @@ -1,380 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newUpdateFunc(t Transport) Update { - return func(index string, id string, body io.Reader, o ...func(*UpdateRequest)) (*Response, error) { - var r = UpdateRequest{Index: index, DocumentID: id, Body: body} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// Update updates a document with a script or partial document. -// -// -type Update func(index string, id string, body io.Reader, o ...func(*UpdateRequest)) (*Response, error) - -// UpdateRequest configures the Update API request. -// -type UpdateRequest struct { - Index string - DocumentID string - - Body io.Reader - - IfPrimaryTerm *int - IfSeqNo *int - Lang string - Refresh string - RequireAlias *bool - RetryOnConflict *int - Routing string - Source interface{} - SourceExcludes []string - SourceIncludes []string - Timeout time.Duration - WaitForActiveShards string - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r UpdateRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(r.Index) + 1 + len(r.DocumentID) + 1 + len("_update")) - path.WriteString("/") - path.WriteString(r.Index) - path.WriteString("/") - path.WriteString("_update") - path.WriteString("/") - path.WriteString(r.DocumentID) - - params = make(map[string]string) - - if r.IfPrimaryTerm != nil { - params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10) - } - - if r.IfSeqNo != nil { - params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10) - } - - if r.Lang != "" { - params["lang"] = r.Lang - } - - if r.Refresh != "" { - params["refresh"] = r.Refresh - } - - if r.RequireAlias != nil { - params["require_alias"] = strconv.FormatBool(*r.RequireAlias) - } - - if r.RetryOnConflict != nil { - params["retry_on_conflict"] = strconv.FormatInt(int64(*r.RetryOnConflict), 10) - } - - if r.Routing != "" { - params["routing"] = r.Routing - } - - if source, ok := r.Source.(bool); ok { - params["_source"] = strconv.FormatBool(source) - } else if source, ok := r.Source.(string); ok && source != "" { - params["_source"] = source - } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { - params["_source"] = strings.Join(sources, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f Update) WithContext(v context.Context) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.ctx = v - } -} - -// WithIfPrimaryTerm - only perform the update operation if the last operation that has changed the document has the specified primary term. -// -func (f Update) WithIfPrimaryTerm(v int) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.IfPrimaryTerm = &v - } -} - -// WithIfSeqNo - only perform the update operation if the last operation that has changed the document has the specified sequence number. -// -func (f Update) WithIfSeqNo(v int) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.IfSeqNo = &v - } -} - -// WithLang - the script language (default: painless). -// -func (f Update) WithLang(v string) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.Lang = v - } -} - -// WithRefresh - if `true` then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes.. -// -func (f Update) WithRefresh(v string) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.Refresh = v - } -} - -// WithRequireAlias - when true, requires destination is an alias. default is false. -// -func (f Update) WithRequireAlias(v bool) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.RequireAlias = &v - } -} - -// WithRetryOnConflict - specify how many times should the operation be retried when a conflict occurs (default: 0). -// -func (f Update) WithRetryOnConflict(v int) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.RetryOnConflict = &v - } -} - -// WithRouting - specific routing value. -// -func (f Update) WithRouting(v string) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.Routing = v - } -} - -// WithSource - true or false to return the _source field or not, or a list of fields to return. -// -func (f Update) WithSource(v interface{}) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.Source = v - } -} - -// WithSourceExcludes - a list of fields to exclude from the returned _source field. -// -func (f Update) WithSourceExcludes(v ...string) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - a list of fields to extract and return from the _source field. -// -func (f Update) WithSourceIncludes(v ...string) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.SourceIncludes = v - } -} - -// WithTimeout - explicit operation timeout. -// -func (f Update) WithTimeout(v time.Duration) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.Timeout = v - } -} - -// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the update operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1). -// -func (f Update) WithWaitForActiveShards(v string) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.WaitForActiveShards = v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f Update) WithPretty() func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f Update) WithHuman() func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f Update) WithErrorTrace() func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f Update) WithFilterPath(v ...string) func(*UpdateRequest) { - return func(r *UpdateRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f Update) WithHeader(h map[string]string) func(*UpdateRequest) { - return func(r *UpdateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f Update) WithOpaqueID(s string) func(*UpdateRequest) { - return func(r *UpdateRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.update_by_query.go b/opensearchapi/api.update_by_query.go deleted file mode 100644 index 2b6103878..000000000 --- a/opensearchapi/api.update_by_query.go +++ /dev/null @@ -1,686 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "fmt" - "io" - "net/http" - "strconv" - "strings" - "time" -) - -func newUpdateByQueryFunc(t Transport) UpdateByQuery { - return func(index []string, o ...func(*UpdateByQueryRequest)) (*Response, error) { - var r = UpdateByQueryRequest{Index: index} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// UpdateByQuery performs an update on every document in the index without changing the source, -// for example to pick up a mapping change. -// -// -type UpdateByQuery func(index []string, o ...func(*UpdateByQueryRequest)) (*Response, error) - -// UpdateByQueryRequest configures the Update By Query API request. -// -type UpdateByQueryRequest struct { - Index []string - - Body io.Reader - - AllowNoIndices *bool - Analyzer string - AnalyzeWildcard *bool - Conflicts string - DefaultOperator string - Df string - ExpandWildcards string - From *int - IgnoreUnavailable *bool - Lenient *bool - MaxDocs *int - Pipeline string - Preference string - Query string - Refresh *bool - RequestCache *bool - RequestsPerSecond *int - Routing []string - Scroll time.Duration - ScrollSize *int - SearchTimeout time.Duration - SearchType string - Size *int - Slices interface{} - Sort []string - Source interface{} - SourceExcludes []string - SourceIncludes []string - Stats []string - TerminateAfter *int - Timeout time.Duration - Version *bool - VersionType *bool - WaitForActiveShards string - WaitForCompletion *bool - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r UpdateByQueryRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len(strings.Join(r.Index, ",")) + 1 + len("_update_by_query")) - path.WriteString("/") - path.WriteString(strings.Join(r.Index, ",")) - path.WriteString("/") - path.WriteString("_update_by_query") - - params = make(map[string]string) - - if r.AllowNoIndices != nil { - params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) - } - - if r.Analyzer != "" { - params["analyzer"] = r.Analyzer - } - - if r.AnalyzeWildcard != nil { - params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) - } - - if r.Conflicts != "" { - params["conflicts"] = r.Conflicts - } - - if r.DefaultOperator != "" { - params["default_operator"] = r.DefaultOperator - } - - if r.Df != "" { - params["df"] = r.Df - } - - if r.ExpandWildcards != "" { - params["expand_wildcards"] = r.ExpandWildcards - } - - if r.From != nil { - params["from"] = strconv.FormatInt(int64(*r.From), 10) - } - - if r.IgnoreUnavailable != nil { - params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) - } - - if r.Lenient != nil { - params["lenient"] = strconv.FormatBool(*r.Lenient) - } - - if r.MaxDocs != nil { - params["max_docs"] = strconv.FormatInt(int64(*r.MaxDocs), 10) - } - - if r.Pipeline != "" { - params["pipeline"] = r.Pipeline - } - - if r.Preference != "" { - params["preference"] = r.Preference - } - - if r.Query != "" { - params["q"] = r.Query - } - - if r.Refresh != nil { - params["refresh"] = strconv.FormatBool(*r.Refresh) - } - - if r.RequestCache != nil { - params["request_cache"] = strconv.FormatBool(*r.RequestCache) - } - - if r.RequestsPerSecond != nil { - params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) - } - - if len(r.Routing) > 0 { - params["routing"] = strings.Join(r.Routing, ",") - } - - if r.Scroll != 0 { - params["scroll"] = formatDuration(r.Scroll) - } - - if r.ScrollSize != nil { - params["scroll_size"] = strconv.FormatInt(int64(*r.ScrollSize), 10) - } - - if r.SearchTimeout != 0 { - params["search_timeout"] = formatDuration(r.SearchTimeout) - } - - if r.SearchType != "" { - params["search_type"] = r.SearchType - } - - if r.Size != nil { - params["size"] = strconv.FormatInt(int64(*r.Size), 10) - } - - if r.Slices != nil { - params["slices"] = fmt.Sprintf("%v", r.Slices) - } - - if len(r.Sort) > 0 { - params["sort"] = strings.Join(r.Sort, ",") - } - - if source, ok := r.Source.(bool); ok { - params["_source"] = strconv.FormatBool(source) - } else if source, ok := r.Source.(string); ok && source != "" { - params["_source"] = source - } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { - params["_source"] = strings.Join(sources, ",") - } - - if len(r.SourceExcludes) > 0 { - params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") - } - - if len(r.SourceIncludes) > 0 { - params["_source_includes"] = strings.Join(r.SourceIncludes, ",") - } - - if len(r.Stats) > 0 { - params["stats"] = strings.Join(r.Stats, ",") - } - - if r.TerminateAfter != nil { - params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) - } - - if r.Timeout != 0 { - params["timeout"] = formatDuration(r.Timeout) - } - - if r.Version != nil { - params["version"] = strconv.FormatBool(*r.Version) - } - - if r.VersionType != nil { - params["version_type"] = strconv.FormatBool(*r.VersionType) - } - - if r.WaitForActiveShards != "" { - params["wait_for_active_shards"] = r.WaitForActiveShards - } - - if r.WaitForCompletion != nil { - params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), r.Body) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if r.Body != nil { - req.Header[headerContentType] = headerContentTypeJSON - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f UpdateByQuery) WithContext(v context.Context) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.ctx = v - } -} - -// WithBody - The search definition using the Query DSL. -// -func (f UpdateByQuery) WithBody(v io.Reader) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Body = v - } -} - -// WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified). -// -func (f UpdateByQuery) WithAllowNoIndices(v bool) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.AllowNoIndices = &v - } -} - -// WithAnalyzer - the analyzer to use for the query string. -// -func (f UpdateByQuery) WithAnalyzer(v string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Analyzer = v - } -} - -// WithAnalyzeWildcard - specify whether wildcard and prefix queries should be analyzed (default: false). -// -func (f UpdateByQuery) WithAnalyzeWildcard(v bool) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.AnalyzeWildcard = &v - } -} - -// WithConflicts - what to do when the update by query hits version conflicts?. -// -func (f UpdateByQuery) WithConflicts(v string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Conflicts = v - } -} - -// WithDefaultOperator - the default operator for query string query (and or or). -// -func (f UpdateByQuery) WithDefaultOperator(v string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.DefaultOperator = v - } -} - -// WithDf - the field to use as default where no field prefix is given in the query string. -// -func (f UpdateByQuery) WithDf(v string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Df = v - } -} - -// WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both.. -// -func (f UpdateByQuery) WithExpandWildcards(v string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.ExpandWildcards = v - } -} - -// WithFrom - starting offset (default: 0). -// -func (f UpdateByQuery) WithFrom(v int) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.From = &v - } -} - -// WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed). -// -func (f UpdateByQuery) WithIgnoreUnavailable(v bool) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.IgnoreUnavailable = &v - } -} - -// WithLenient - specify whether format-based query failures (such as providing text to a numeric field) should be ignored. -// -func (f UpdateByQuery) WithLenient(v bool) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Lenient = &v - } -} - -// WithMaxDocs - maximum number of documents to process (default: all documents). -// -func (f UpdateByQuery) WithMaxDocs(v int) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.MaxDocs = &v - } -} - -// WithPipeline - ingest pipeline to set on index requests made by this action. (default: none). -// -func (f UpdateByQuery) WithPipeline(v string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Pipeline = v - } -} - -// WithPreference - specify the node or shard the operation should be performed on (default: random). -// -func (f UpdateByQuery) WithPreference(v string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Preference = v - } -} - -// WithQuery - query in the lucene query string syntax. -// -func (f UpdateByQuery) WithQuery(v string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Query = v - } -} - -// WithRefresh - should the affected indexes be refreshed?. -// -func (f UpdateByQuery) WithRefresh(v bool) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Refresh = &v - } -} - -// WithRequestCache - specify if request cache should be used for this request or not, defaults to index level setting. -// -func (f UpdateByQuery) WithRequestCache(v bool) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.RequestCache = &v - } -} - -// WithRequestsPerSecond - the throttle to set on this request in sub-requests per second. -1 means no throttle.. -// -func (f UpdateByQuery) WithRequestsPerSecond(v int) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.RequestsPerSecond = &v - } -} - -// WithRouting - a list of specific routing values. -// -func (f UpdateByQuery) WithRouting(v ...string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Routing = v - } -} - -// WithScroll - specify how long a consistent view of the index should be maintained for scrolled search. -// -func (f UpdateByQuery) WithScroll(v time.Duration) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Scroll = v - } -} - -// WithScrollSize - size on the scroll request powering the update by query. -// -func (f UpdateByQuery) WithScrollSize(v int) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.ScrollSize = &v - } -} - -// WithSearchTimeout - explicit timeout for each search request. defaults to no timeout.. -// -func (f UpdateByQuery) WithSearchTimeout(v time.Duration) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.SearchTimeout = v - } -} - -// WithSearchType - search operation type. -// -func (f UpdateByQuery) WithSearchType(v string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.SearchType = v - } -} - -// WithSize - deprecated, please use `max_docs` instead. -// -func (f UpdateByQuery) WithSize(v int) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Size = &v - } -} - -// WithSlices - the number of slices this task should be divided into. defaults to 1, meaning the task isn't sliced into subtasks. can be set to `auto`.. -// -func (f UpdateByQuery) WithSlices(v interface{}) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Slices = v - } -} - -// WithSort - a list of : pairs. -// -func (f UpdateByQuery) WithSort(v ...string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Sort = v - } -} - -// WithSource - true or false to return the _source field or not, or a list of fields to return. -// -func (f UpdateByQuery) WithSource(v interface{}) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Source = v - } -} - -// WithSourceExcludes - a list of fields to exclude from the returned _source field. -// -func (f UpdateByQuery) WithSourceExcludes(v ...string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.SourceExcludes = v - } -} - -// WithSourceIncludes - a list of fields to extract and return from the _source field. -// -func (f UpdateByQuery) WithSourceIncludes(v ...string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.SourceIncludes = v - } -} - -// WithStats - specific 'tag' of the request for logging and statistical purposes. -// -func (f UpdateByQuery) WithStats(v ...string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Stats = v - } -} - -// WithTerminateAfter - the maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early.. -// -func (f UpdateByQuery) WithTerminateAfter(v int) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.TerminateAfter = &v - } -} - -// WithTimeout - time each individual bulk request should wait for shards that are unavailable.. -// -func (f UpdateByQuery) WithTimeout(v time.Duration) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Timeout = v - } -} - -// WithVersion - specify whether to return document version as part of a hit. -// -func (f UpdateByQuery) WithVersion(v bool) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Version = &v - } -} - -// WithVersionType - should the document increment the version number (internal) on hit or not (reindex). -// -func (f UpdateByQuery) WithVersionType(v bool) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.VersionType = &v - } -} - -// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the update by query operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1). -// -func (f UpdateByQuery) WithWaitForActiveShards(v string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.WaitForActiveShards = v - } -} - -// WithWaitForCompletion - should the request should block until the update by query operation is complete.. -// -func (f UpdateByQuery) WithWaitForCompletion(v bool) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.WaitForCompletion = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f UpdateByQuery) WithPretty() func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f UpdateByQuery) WithHuman() func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f UpdateByQuery) WithErrorTrace() func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f UpdateByQuery) WithFilterPath(v ...string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f UpdateByQuery) WithHeader(h map[string]string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f UpdateByQuery) WithOpaqueID(s string) func(*UpdateByQueryRequest) { - return func(r *UpdateByQueryRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api.update_by_query_rethrottle.go b/opensearchapi/api.update_by_query_rethrottle.go deleted file mode 100644 index 9cc093902..000000000 --- a/opensearchapi/api.update_by_query_rethrottle.go +++ /dev/null @@ -1,224 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "context" - "net/http" - "strconv" - "strings" -) - -func newUpdateByQueryRethrottleFunc(t Transport) UpdateByQueryRethrottle { - return func(task_id string, requests_per_second *int, o ...func(*UpdateByQueryRethrottleRequest)) (*Response, error) { - var r = UpdateByQueryRethrottleRequest{TaskID: task_id, RequestsPerSecond: requests_per_second} - for _, f := range o { - f(&r) - } - return r.Do(r.ctx, t) - } -} - -// ----- API Definition ------------------------------------------------------- - -// UpdateByQueryRethrottle changes the number of requests per second for a particular Update By Query operation. -// -// -type UpdateByQueryRethrottle func(task_id string, requests_per_second *int, o ...func(*UpdateByQueryRethrottleRequest)) (*Response, error) - -// UpdateByQueryRethrottleRequest configures the Update By Query Rethrottle API request. -// -type UpdateByQueryRethrottleRequest struct { - TaskID string - - RequestsPerSecond *int - - Pretty bool - Human bool - ErrorTrace bool - FilterPath []string - - Header http.Header - - ctx context.Context -} - -// Do executes the request and returns response or error. -// -func (r UpdateByQueryRethrottleRequest) Do(ctx context.Context, transport Transport) (*Response, error) { - var ( - method string - path strings.Builder - params map[string]string - ) - - method = "POST" - - path.Grow(1 + len("_update_by_query") + 1 + len(r.TaskID) + 1 + len("_rethrottle")) - path.WriteString("/") - path.WriteString("_update_by_query") - path.WriteString("/") - path.WriteString(r.TaskID) - path.WriteString("/") - path.WriteString("_rethrottle") - - params = make(map[string]string) - - if r.RequestsPerSecond != nil { - params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) - } - - if r.Pretty { - params["pretty"] = "true" - } - - if r.Human { - params["human"] = "true" - } - - if r.ErrorTrace { - params["error_trace"] = "true" - } - - if len(r.FilterPath) > 0 { - params["filter_path"] = strings.Join(r.FilterPath, ",") - } - - req, err := newRequest(method, path.String(), nil) - if err != nil { - return nil, err - } - - if len(params) > 0 { - q := req.URL.Query() - for k, v := range params { - q.Set(k, v) - } - req.URL.RawQuery = q.Encode() - } - - if len(r.Header) > 0 { - if len(req.Header) == 0 { - req.Header = r.Header - } else { - for k, vv := range r.Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - } - } - - if ctx != nil { - req = req.WithContext(ctx) - } - - res, err := transport.Perform(req) - if err != nil { - return nil, err - } - - response := Response{ - StatusCode: res.StatusCode, - Body: res.Body, - Header: res.Header, - } - - return &response, response.Err() -} - -// WithContext sets the request context. -// -func (f UpdateByQueryRethrottle) WithContext(v context.Context) func(*UpdateByQueryRethrottleRequest) { - return func(r *UpdateByQueryRethrottleRequest) { - r.ctx = v - } -} - -// WithRequestsPerSecond - the throttle to set on this request in floating sub-requests per second. -1 means set no throttle.. -// -func (f UpdateByQueryRethrottle) WithRequestsPerSecond(v int) func(*UpdateByQueryRethrottleRequest) { - return func(r *UpdateByQueryRethrottleRequest) { - r.RequestsPerSecond = &v - } -} - -// WithPretty makes the response body pretty-printed. -// -func (f UpdateByQueryRethrottle) WithPretty() func(*UpdateByQueryRethrottleRequest) { - return func(r *UpdateByQueryRethrottleRequest) { - r.Pretty = true - } -} - -// WithHuman makes statistical values human-readable. -// -func (f UpdateByQueryRethrottle) WithHuman() func(*UpdateByQueryRethrottleRequest) { - return func(r *UpdateByQueryRethrottleRequest) { - r.Human = true - } -} - -// WithErrorTrace includes the stack trace for errors in the response body. -// -func (f UpdateByQueryRethrottle) WithErrorTrace() func(*UpdateByQueryRethrottleRequest) { - return func(r *UpdateByQueryRethrottleRequest) { - r.ErrorTrace = true - } -} - -// WithFilterPath filters the properties of the response body. -// -func (f UpdateByQueryRethrottle) WithFilterPath(v ...string) func(*UpdateByQueryRethrottleRequest) { - return func(r *UpdateByQueryRethrottleRequest) { - r.FilterPath = v - } -} - -// WithHeader adds the headers to the HTTP request. -// -func (f UpdateByQueryRethrottle) WithHeader(h map[string]string) func(*UpdateByQueryRethrottleRequest) { - return func(r *UpdateByQueryRethrottleRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - for k, v := range h { - r.Header.Add(k, v) - } - } -} - -// WithOpaqueID adds the X-Opaque-Id header to the HTTP request. -// -func (f UpdateByQueryRethrottle) WithOpaqueID(s string) func(*UpdateByQueryRethrottleRequest) { - return func(r *UpdateByQueryRethrottleRequest) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set("X-Opaque-Id", s) - } -} diff --git a/opensearchapi/api_aliases-params.go b/opensearchapi/api_aliases-params.go new file mode 100644 index 000000000..4381a3f53 --- /dev/null +++ b/opensearchapi/api_aliases-params.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "time" + +// AliasesParams represents possible parameters for the AliasesReq +type AliasesParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r AliasesParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_aliases.go b/opensearchapi/api_aliases.go new file mode 100644 index 000000000..747b60b11 --- /dev/null +++ b/opensearchapi/api_aliases.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// Aliases executes an /_aliases request with the required AliasesReq +func (c Client) Aliases(ctx context.Context, req AliasesReq) (*AliasesResp, error) { + var ( + data AliasesResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// AliasesReq represents possible options for the / request +type AliasesReq struct { + Body io.Reader + + Header http.Header + Params AliasesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r AliasesReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_aliases", + r.Body, + r.Params.get(), + r.Header, + ) +} + +// AliasesResp represents the returned struct of the / response +type AliasesResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r AliasesResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_aliases_test.go b/opensearchapi/api_aliases_test.go new file mode 100644 index 000000000..c78d9efb8 --- /dev/null +++ b/opensearchapi/api_aliases_test.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestAliases(t *testing.T) { + t.Run("Aliases", func(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + index := "test-aliases" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{index}}) + }) + + _, err = client.Indices.Create(nil, opensearchapi.IndicesCreateReq{Index: index}) + require.Nil(t, err) + + t.Run("with request", func(t *testing.T) { + resp, err := client.Aliases( + nil, + opensearchapi.AliasesReq{ + Body: strings.NewReader(`{"actions":[{"add":{"index":"test-aliases","alias":"logs"}},{"remove":{"index":"test-aliases","alias":"logs"}}]}`), + }, + ) + require.Nil(t, err) + require.NotEmpty(t, resp) + require.NotEmpty(t, resp.Inspect().Response) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.Aliases(nil, opensearchapi.AliasesReq{}) + require.NotNil(t, err) + require.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) + }) +} diff --git a/opensearchapi/api_bulk-params.go b/opensearchapi/api_bulk-params.go new file mode 100644 index 000000000..580aa137c --- /dev/null +++ b/opensearchapi/api_bulk-params.go @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// BulkParams represents possible parameters for the BulkReq +type BulkParams struct { + Pipeline string + Refresh string + RequireAlias *bool + Routing string + Source any + SourceExcludes []string + SourceIncludes []string + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r BulkParams) get() map[string]string { + params := make(map[string]string) + + if r.Pipeline != "" { + params["pipeline"] = r.Pipeline + } + + if r.Refresh != "" { + params["refresh"] = r.Refresh + } + + if r.RequireAlias != nil { + params["require_alias"] = strconv.FormatBool(*r.RequireAlias) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_bulk.go b/opensearchapi/api_bulk.go new file mode 100644 index 000000000..717dff45d --- /dev/null +++ b/opensearchapi/api_bulk.go @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// Bulk executes a /_bulk request with the needed BulkReq +func (c Client) Bulk(ctx context.Context, req BulkReq) (*BulkResp, error) { + var ( + data BulkResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// BulkReq represents possible options for the /_bulk request +type BulkReq struct { + Index string + Body io.Reader + Header http.Header + Params BulkParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r BulkReq) GetRequest() (*http.Request, error) { + var path strings.Builder + //nolint:gomnd // 7 is the max number of static chars + path.Grow(7 + len(r.Index)) + + if len(r.Index) > 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + + path.WriteString("/_bulk") + + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// BulkResp represents the returned struct of the /_bulk response +type BulkResp struct { + Took int `json:"took"` + Errors bool `json:"errors"` + Items []map[string]BulkRespItem `json:"items"` + response *opensearch.Response +} + +// BulkRespItem represents an item of the BulkResp +type BulkRespItem struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Type string `json:"_type"` // Deprecated field + Result string `json:"result"` + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + Status int `json:"status"` + Error *struct { + Type string `json:"type"` + Reason string `json:"reason"` + Cause struct { + Type string `json:"type"` + Reason string `json:"reason"` + ScriptStack *[]string `json:"script_stack,omitempty"` + Script *string `json:"script,omitempty"` + Lang *string `json:"lang,omitempty"` + Position *struct { + Offset int `json:"offset"` + Start int `json:"start"` + End int `json:"end"` + } `json:"position,omitempty"` + Cause *struct { + Type string `json:"type"` + Reason string `json:"reason"` + } `json:"caused_by"` + } `json:"caused_by,omitempty"` + } `json:"error,omitempty"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r BulkResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_bulk_test.go b/opensearchapi/api_bulk_test.go new file mode 100644 index 000000000..a1d6ddb03 --- /dev/null +++ b/opensearchapi/api_bulk_test.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestBulkClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + index := "test-bulk" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{index}}) + }) + + tests := []struct { + Name string + Request opensearchapi.BulkReq + }{ + { + Name: "with index", + Request: opensearchapi.BulkReq{ + Index: index, + Body: strings.NewReader("{\"index\": {}}\n{\"test\": 1234}\n{\"create\": {}}\n{\"test\": 5678}\n"), + }, + }, + { + Name: "without index", + Request: opensearchapi.BulkReq{ + Body: strings.NewReader( + fmt.Sprintf("{\"index\": {\"_index\": \"%s\"}}\n{\"test\": 1234}\n{\"create\": {\"_index\": \"%s\"}}\n{\"test\": 5678}\n", index, index), + ), + }, + }, + } + + for _, test := range tests { + t.Run(test.Name, func(t *testing.T) { + res, err := client.Bulk( + nil, + test.Request, + ) + require.Nil(t, err) + assert.NotEmpty(t, res) + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + }) + } + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.Bulk(nil, opensearchapi.BulkReq{Index: index}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_cat-aliases-params.go b/opensearchapi/api_cat-aliases-params.go new file mode 100644 index 000000000..c3bf97ac6 --- /dev/null +++ b/opensearchapi/api_cat-aliases-params.go @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatAliasesParams represents possible parameters for the CatAliasesReq +type CatAliasesParams struct { + ExpandWildcards string + H []string + Local *bool + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatAliasesParams) get() map[string]string { + params := make(map[string]string) + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-aliases.go b/opensearchapi/api_cat-aliases.go new file mode 100644 index 000000000..004f2c05b --- /dev/null +++ b/opensearchapi/api_cat-aliases.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatAliasesReq represent possible options for the /_cat/aliases request +type CatAliasesReq struct { + Aliases []string + Header http.Header + Params CatAliasesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatAliasesReq) GetRequest() (*http.Request, error) { + aliases := strings.Join(r.Aliases, ",") + var path strings.Builder + path.Grow(len("/_cat/aliases/") + len(aliases)) + path.WriteString("/_cat/aliases") + if len(r.Aliases) > 0 { + path.WriteString("/") + path.WriteString(aliases) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatAliasesResp represents the returned struct of the /_cat/aliases response +type CatAliasesResp struct { + Aliases []CatAliasResp + response *opensearch.Response +} + +// CatAliasResp represents one index of the CatAliasesResp +type CatAliasResp struct { + Alias string `json:"alias"` + Index string `json:"index"` + Filter string `json:"filter"` + RoutingIndex string `json:"routing.index"` + RoutingSearch string `json:"routing.search"` + IsWriteIndex string `json:"is_write_index"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatAliasesResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-allocation-params.go b/opensearchapi/api_cat-allocation-params.go new file mode 100644 index 000000000..6ddc428b2 --- /dev/null +++ b/opensearchapi/api_cat-allocation-params.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatAllocationParams represents possible parameters for the CatAllocationReq +type CatAllocationParams struct { + Bytes string + ExpandWildcards string + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatAllocationParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-allocation.go b/opensearchapi/api_cat-allocation.go new file mode 100644 index 000000000..c01e76470 --- /dev/null +++ b/opensearchapi/api_cat-allocation.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatAllocationReq represent possible options for the /_cat/allocation request +type CatAllocationReq struct { + NodeIDs []string + Header http.Header + Params CatAllocationParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatAllocationReq) GetRequest() (*http.Request, error) { + nodes := strings.Join(r.NodeIDs, ",") + var path strings.Builder + path.Grow(len("/_cat/allocation/") + len(nodes)) + path.WriteString("/_cat/allocation") + if len(r.NodeIDs) > 0 { + path.WriteString("/") + path.WriteString(nodes) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatAllocationsResp represents the returned struct of the /_cat/allocation response +type CatAllocationsResp struct { + Allocations []CatAllocationResp + response *opensearch.Response +} + +// CatAllocationResp represents one index of the CatAllocationResp +type CatAllocationResp struct { + Shards int `json:"shards,string"` + // Pointer of string as the api can returns null for those fileds with Node set to "UNASSIGNED" + DiskIndices *string `json:"disk.indices"` + DiskUsed *string `json:"disk.used"` + DiskAvail *string `json:"disk.avail"` + DiskTotal *string `json:"disk.total"` + DiskPercent *int `json:"disk.percent,string"` + Host *string `json:"host"` + IP *string `json:"ip"` + Node string `json:"node"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatAllocationsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-cluster_manager-params.go b/opensearchapi/api_cat-cluster_manager-params.go new file mode 100644 index 000000000..5324f5e01 --- /dev/null +++ b/opensearchapi/api_cat-cluster_manager-params.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatClusterManagerParams represents possible parameters for the CatClusterManagerReq +type CatClusterManagerParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatClusterManagerParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-cluster_manager.go b/opensearchapi/api_cat-cluster_manager.go new file mode 100644 index 000000000..2a5dd38d4 --- /dev/null +++ b/opensearchapi/api_cat-cluster_manager.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatClusterManagerReq represent possible options for the /_cat/cluster_manager request +type CatClusterManagerReq struct { + Header http.Header + Params CatClusterManagerParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatClusterManagerReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/cluster_manager", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatClusterManagersResp represents the returned struct of the /_cat/cluster_manager response +type CatClusterManagersResp struct { + ClusterManagers []CatClusterManagerResp + response *opensearch.Response +} + +// CatClusterManagerResp represents one index of the CatClusterManagerResp +type CatClusterManagerResp struct { + ID string `json:"id"` + Host string `json:"host"` + IP string `json:"ip"` + Node string `json:"node"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatClusterManagersResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-count-params.go b/opensearchapi/api_cat-count-params.go new file mode 100644 index 000000000..d734ec1ce --- /dev/null +++ b/opensearchapi/api_cat-count-params.go @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatCountParams represents possible parameters for the CatCountReq +type CatCountParams struct { + H []string + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatCountParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-count.go b/opensearchapi/api_cat-count.go new file mode 100644 index 000000000..699e01b4b --- /dev/null +++ b/opensearchapi/api_cat-count.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatCountReq represent possible options for the /_cat/count request +type CatCountReq struct { + Indices []string + Header http.Header + Params CatCountParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatCountReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("/_cat/count/") + len(indices)) + path.WriteString("/_cat/count") + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatCountsResp represents the returned struct of the /_cat/count response +type CatCountsResp struct { + Counts []CatCountResp + response *opensearch.Response +} + +// CatCountResp represents one index of the CatCountResp +type CatCountResp struct { + Epoch int `json:"epoch,string"` + Timestamp string `json:"timestamp"` + Count int `json:"count,string"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatCountsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-fielddata-params.go b/opensearchapi/api_cat-fielddata-params.go new file mode 100644 index 000000000..4777669c5 --- /dev/null +++ b/opensearchapi/api_cat-fielddata-params.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatFieldDataParams represents possible parameters for the CatFieldDataReq +type CatFieldDataParams struct { + Bytes string + H []string + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatFieldDataParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-fielddata.go b/opensearchapi/api_cat-fielddata.go new file mode 100644 index 000000000..4b9f3edb5 --- /dev/null +++ b/opensearchapi/api_cat-fielddata.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatFieldDataReq represent possible options for the /_cat/fielddata request +type CatFieldDataReq struct { + FieldData []string + Header http.Header + Params CatFieldDataParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatFieldDataReq) GetRequest() (*http.Request, error) { + fielddata := strings.Join(r.FieldData, ",") + var path strings.Builder + path.Grow(len("/_cat/fielddata/") + len(fielddata)) + path.WriteString("/_cat/fielddata") + if len(r.FieldData) > 0 { + path.WriteString("/") + path.WriteString(fielddata) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatFieldDataResp represents the returned struct of the /_cat/fielddata response +type CatFieldDataResp struct { + FieldData []CatFieldDataItemResp + response *opensearch.Response +} + +// CatFieldDataItemResp represents one index of the CatFieldDataResp +type CatFieldDataItemResp struct { + ID string `json:"id"` + Host string `json:"host"` + IP string `json:"ip"` + Node string `json:"node"` + Field string `json:"field"` + Size string `json:"size"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatFieldDataResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-health-params.go b/opensearchapi/api_cat-health-params.go new file mode 100644 index 000000000..3c4233365 --- /dev/null +++ b/opensearchapi/api_cat-health-params.go @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatHealthParams represents possible parameters for the CatHealthReq +type CatHealthParams struct { + H []string + Sort []string + Time string + TS *bool + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatHealthParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.TS != nil { + params["ts"] = strconv.FormatBool(*r.TS) + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-health.go b/opensearchapi/api_cat-health.go new file mode 100644 index 000000000..3c73d82f4 --- /dev/null +++ b/opensearchapi/api_cat-health.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatHealthReq represent possible options for the /_cat/health request +type CatHealthReq struct { + Header http.Header + Params CatHealthParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatHealthReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/health", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatHealthResp represents the returned struct of the /_cat/health response +type CatHealthResp struct { + Health []CatHealthItemResp + response *opensearch.Response +} + +// CatHealthItemResp represents one index of the CatHealthResp +type CatHealthItemResp struct { + Epoch int `json:"epoch,string"` + Timestamp string `json:"timestamp"` + Cluster string `json:"cluster"` + Status string `json:"status"` + NodeTotal int `json:"node.total,string"` + NodeData int `json:"node.data,string"` + DiscoveredMaster bool `json:"discovered_master,string"` + DiscoveredClusterManager bool `json:"discovered_cluster_manager,string"` + Shards int `json:"shards,string"` + Primary int `json:"pri,string"` + Relocating int `json:"relo,string"` + Initializing int `json:"init,string"` + Unassigned int `json:"unassign,string"` + PendingTasks int `json:"pending_tasks,string"` + MaxTaskWaitTime string `json:"max_task_wait_time"` + ActiveShardsPercent string `json:"active_shards_percent"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatHealthResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-indices-params.go b/opensearchapi/api_cat-indices-params.go new file mode 100644 index 000000000..cca17ccdb --- /dev/null +++ b/opensearchapi/api_cat-indices-params.go @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatIndicesParams represents possible parameters for the CatIndicesReq +type CatIndicesParams struct { + Bytes string + ExpandWildcards string + H []string + Health string + IncludeUnloadedSegments *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Primary *bool + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatIndicesParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Health != "" { + params["health"] = r.Health + } + + if r.IncludeUnloadedSegments != nil { + params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Primary != nil { + params["pri"] = strconv.FormatBool(*r.Primary) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-indices.go b/opensearchapi/api_cat-indices.go new file mode 100644 index 000000000..e4a42c8b4 --- /dev/null +++ b/opensearchapi/api_cat-indices.go @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatIndicesReq represent possible options for the /_cat/indices request +type CatIndicesReq struct { + Indices []string + Header http.Header + Params CatIndicesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatIndicesReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("/_cat/indices/") + len(indices)) + path.WriteString("/_cat/indices") + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatIndicesResp represents the returned struct of the /_cat/indices response +type CatIndicesResp struct { + Indices []CatIndexResp + response *opensearch.Response +} + +// CatIndexResp represents one index of the CatIndicesResp +type CatIndexResp struct { + Health string `json:"health"` + Status string `json:"status"` + Index string `json:"index"` + UUID string `json:"uuid"` + Primary int `json:"pri,string"` + Replica int `json:"rep,string"` + DocsCount *int `json:"docs.count,string"` + DocDeleted *int `json:"docs.deleted,string"` + CreationDate int `json:"creation.date,string"` + CreationDateString string `json:"creation.date.string"` + // Pointer as newly created indices can return null + StoreSize *string `json:"store.size"` + PrimaryStoreSize *string `json:"pri.store.size"` + CompletionSize *string `json:"completion.size"` + PrimaryCompletionSize *string `json:"pri.completion.size"` + FieldDataMemorySize *string `json:"fielddata.memory_size"` + PrimaryFieldDataMemorySize *string `json:"pri.fielddata.memory_size"` + FieldDataEvictions *int `json:"fielddata.evictions,string"` + PrimaryFieldDataEvictions *int `json:"pri.fielddata.evictions,string"` + QueryCacheMemorySize *string `json:"query_cache.memory_size"` + PrimaryQueryCacheMemorySize *string `json:"pri.query_cache.memory_size"` + QueryCacheEvictions *int `json:"query_cache.evictions,string"` + PrimaryQueryCacheEvictions *int `json:"pri.query_cache.evictions,string"` + RequestCacheMemorySize *string `json:"request_cache.memory_size"` + PrimaryRequestCacheMemorySize *string `json:"pri.request_cache.memory_size"` + RequestCacheEvictions *int `json:"request_cache.evictions,string"` + PrimaryRequestCacheEvictions *int `json:"pri.request_cache.evictions,string"` + RequestCacheHitCount *int `json:"request_cache.hit_count,string"` + PrimaryRequestCacheHitCount *int `json:"pri.request_cache.hit_count,string"` + RequestCacheMissCount *int `json:"request_cache.miss_count,string"` + PrimaryRequestCacheMissCount *int `json:"pri.request_cache.miss_count,string"` + FlushTotal *int `json:"flush.total,string"` + PrimaryFlushTotal *int `json:"pri.flush.total,string"` + FlushTime *string `json:"flush.total_time"` + PrimaryFlushTime *string `json:"pri.flush.total_time"` + GetCurrent *int `json:"get.current,string"` + PrimaryGetCurrent *int `json:"pri.get.current,string"` + GetTime *string `json:"get.time"` + PrimaryGetTime *string `json:"pri.get.time"` + GetTotal *int `json:"get.total,string"` + PrimaryGetTotal *int `json:"pri.get.total,string"` + GetExistsTime *string `json:"get.exists_time"` + PrimaryGetExistsTime *string `json:"pri.get.exists_time"` + GetExistsTotal *int `json:"get.exists_total,string"` + PrimaryGetExistsTotal *int `json:"pri.get.exists_total,string"` + GetMissingTime *string `json:"get.missing_time"` + PrimaryGetMissingTime *string `json:"pri.get.missing_time"` + GetMissingTotal *int `json:"get.missing_total,string"` + PrimaryGetMissingTotal *int `json:"pri.get.missing_total,string"` + IndexingDeleteCurrent *int `json:"indexing.delete_current,string"` + PrimaryIndexingDeleteCurrent *int `json:"pri.indexing.delete_current,string"` + IndexingDeleteTime *string `json:"indexing.delete_time"` + PrimaryIndexingDeleteTime *string `json:"pri.indexing.delete_time"` + IndexingDeleteTotal *int `json:"indexing.delete_total,string"` + PrimaryIndexingDeleteTotal *int `json:"pri.indexing.delete_total,string"` + IndexingIndexCurrent *int `json:"indexing.index_current,string"` + PrimaryIndexingIndexCurrent *int `json:"pri.indexing.index_current,string"` + IndexingIndexTime *string `json:"indexing.index_time"` + PrimaryIndexingIndexTime *string `json:"pri.indexing.index_time"` + IndexingIndexTotal *int `json:"indexing.index_total,string"` + PrimaryIndexingIndexTotal *int `json:"pri.indexing.index_total,string"` + IndexingIndexFailed *int `json:"indexing.index_failed,string"` + PrimaryIndexingIndexFailed *int `json:"pri.indexing.index_failed,string"` + MergesCurrent *int `json:"merges.current,string"` + PrimaryMergesCurrent *int `json:"pri.merges.current,string"` + MergesCurrentDocs *int `json:"merges.current_docs,string"` + PrimaryMergesCurrentDocs *int `json:"pri.merges.current_docs,string"` + MergesCurrentSize *string `json:"merges.current_size"` + PrimaryMergesCurrentSize *string `json:"pri.merges.current_size"` + MergesTotal *int `json:"merges.total,string"` + PrimaryMergesTotal *int `json:"pri.merges.total,string"` + MergesTotalDocs *int `json:"merges.total_docs,string"` + PrimaryMergesTotalDocs *int `json:"pri.merges.total_docs,string"` + MergesTotalSize *string `json:"merges.total_size"` + PrimaryMergesTotalSize *string `json:"pri.merges.total_size"` + MergesTotalTime *string `json:"merges.total_time"` + PrimaryMergesTotalTime *string `json:"pri.merges.total_time"` + RefreshTotal *int `json:"refresh.total,string"` + PrimaryRefreshTotal *int `json:"pri.refresh.total,string"` + RefreshTime *string `json:"refresh.time"` + PrimaryRefreshTime *string `json:"pri.refresh.time"` + RefreshExternalTotal *int `json:"refresh.external_total,string"` + PrimaryRefreshExternalTotal *int `json:"pri.refresh.external_total,string"` + RefreshExternalTime *string `json:"refresh.external_time"` + PrimaryRefreshExternalTime *string `json:"pri.refresh.external_time"` + RefreshListeners *int `json:"refresh.listeners,string"` + PrimaryRefreshListeners *int `json:"pri.refresh.listeners,string"` + SearchFetchCurrent *int `json:"search.fetch_current,string"` + PrimarySearchFetchCurrent *int `json:"pri.search.fetch_current,string"` + SearchFetchTime *string `json:"search.fetch_time"` + PrimarySearchFetchTime *string `json:"pri.search.fetch_time"` + SearchFetchTotal *int `json:"search.fetch_total,string"` + PrimarySearchFetchTotal *int `json:"pri.search.fetch_total,string"` + SearchOpenContexts *int `json:"search.open_contexts,string"` + PrimarySearchOpenContexts *int `json:"pri.search.open_contexts,string"` + SearchQueryCurrent *int `json:"search.query_current,string"` + PrimarySearchQueryCurrent *int `json:"pri.search.query_current,string"` + SearchQueryTime *string `json:"search.query_time"` + PrimarySearchQueryTime *string `json:"pri.search.query_time"` + SearchQueryTotal *int `json:"search.query_total,string"` + PrimarySearchQueryTotal *int `json:"pri.search.query_total,string"` + SearchScrollCurrent *int `json:"search.scroll_current,string"` + PrimarySearchScrollCurrent *int `json:"pri.search.scroll_current,string"` + SearchScrollTime *string `json:"search.scroll_time"` + PrimarySearchScrollTime *string `json:"pri.search.scroll_time"` + SearchScrollTotal *int `json:"search.scroll_total,string"` + PrimarySearchScrollTotal *int `json:"pri.search.scroll_total,string"` + SearchPointInTimeCurrent *string `json:"search.point_in_time_current"` + PrimarySearchPointInTimeCurrent *string `json:"pri.search.point_in_time_current"` + SearchPointInTimeTime *string `json:"search.point_in_time_time"` + PrimarySearchPointInTimeTime *string `json:"pri.search.point_in_time_time"` + SearchPointInTimeTotal *int `json:"search.point_in_time_total,string"` + PrimarySearchPointInTimeTotal *int `json:"pri.search.point_in_time_total,string"` + SegmentsCount *int `json:"segments.count,string"` + PrimarySegmentsCount *int `json:"pri.segments.count,string"` + SegmentsMemory *string `json:"segments.memory"` + PrimarySegmentsMemory *string `json:"pri.segments.memory"` + SegmentsIndexWriteMemory *string `json:"segments.index_writer_memory"` + PrimarySegmentsIndexWriteMemory *string `json:"pri.segments.index_writer_memory"` + SegmentsVersionMapMemory *string `json:"segments.version_map_memory"` + PrimarySegmentsVersionMapMemory *string `json:"pri.segments.version_map_memory"` + SegmentsFixedBitsetMemory *string `json:"segments.fixed_bitset_memory"` + PrimarySegmentsFixedBitsetMemory *string `json:"pri.segments.fixed_bitset_memory"` + WarmerCurrent *int `json:"warmer.current,string"` + PrimaryWarmerCurrent *int `json:"pri.warmer.current,string"` + WarmerTotal *int `json:"warmer.total,string"` + PrimaryWarmerTotal *int `json:"pri.warmer.total,string"` + WarmerTotalTime *string `json:"warmer.total_time"` + PrimaryWarmerTotalTime *string `json:"pri.warmer.total_time"` + SuggestCurrent *int `json:"suggest.current,string"` + PrimarySuggestCurrent *int `json:"pri.suggest.current,string"` + SuggestTime *string `json:"suggest.time"` + PrimarySuggestTime *string `json:"pri.suggest.time"` + SuggestTotal *int `json:"suggest.total,string"` + PrimarySuggestTotal *int `json:"pri.suggest.total,string"` + MemoryTotal string `json:"memory.total"` + PrimaryMemoryTotal string `json:"pri.memory.total"` + SearchThrottled bool `json:"search.throttled,string"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatIndicesResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-master-params.go b/opensearchapi/api_cat-master-params.go new file mode 100644 index 000000000..1f9eefd2c --- /dev/null +++ b/opensearchapi/api_cat-master-params.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatMasterParams represents possible parameters for the CatMasterReq +type CatMasterParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatMasterParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-master.go b/opensearchapi/api_cat-master.go new file mode 100644 index 000000000..7c4fc0094 --- /dev/null +++ b/opensearchapi/api_cat-master.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatMasterReq represent possible options for the /_cat/master request +type CatMasterReq struct { + Header http.Header + Params CatMasterParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatMasterReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/master", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatMasterResp represents the returned struct of the /_cat/master response +type CatMasterResp struct { + Master []CatMasterItemResp + response *opensearch.Response +} + +// CatMasterItemResp represents one index of the CatMasterResp +type CatMasterItemResp struct { + ID string `json:"id"` + Host string `json:"host"` + IP string `json:"ip"` + Node string `json:"node"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatMasterResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-nodeattrs-params.go b/opensearchapi/api_cat-nodeattrs-params.go new file mode 100644 index 000000000..49e418a92 --- /dev/null +++ b/opensearchapi/api_cat-nodeattrs-params.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatNodeAttrsParams represents possible parameters for the CatNodeAttrsReq +type CatNodeAttrsParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatNodeAttrsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-nodeattrs.go b/opensearchapi/api_cat-nodeattrs.go new file mode 100644 index 000000000..5c4653265 --- /dev/null +++ b/opensearchapi/api_cat-nodeattrs.go @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatNodeAttrsReq represent possible options for the /_cat/nodeattrs request +type CatNodeAttrsReq struct { + Header http.Header + Params CatNodeAttrsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatNodeAttrsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/nodeattrs", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatNodeAttrsResp represents the returned struct of the /_cat/nodeattrs response +type CatNodeAttrsResp struct { + NodeAttrs []CatNodeAttrsItemResp + response *opensearch.Response +} + +// CatNodeAttrsItemResp represents one index of the CatNodeAttrsResp +type CatNodeAttrsItemResp struct { + Node string `json:"node"` + ID string `json:"id"` + PID int `json:"pid,string"` + Host string `json:"host"` + IP string `json:"ip"` + Port int `json:"port,string"` + Attr string `json:"attr"` + Value string `json:"value"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatNodeAttrsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-nodes-params.go b/opensearchapi/api_cat-nodes-params.go new file mode 100644 index 000000000..e986d33ba --- /dev/null +++ b/opensearchapi/api_cat-nodes-params.go @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatNodesParams represents possible parameters for the CatNodesReq +type CatNodesParams struct { + Bytes string + FullID *bool + H []string + IncludeUnloadedSegments *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatNodesParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if r.FullID != nil { + params["full_id"] = strconv.FormatBool(*r.FullID) + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.IncludeUnloadedSegments != nil { + params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-nodes.go b/opensearchapi/api_cat-nodes.go new file mode 100644 index 000000000..5fd40b792 --- /dev/null +++ b/opensearchapi/api_cat-nodes.go @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatNodesReq represent possible options for the /_cat/nodes request +type CatNodesReq struct { + Header http.Header + Params CatNodesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatNodesReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/nodes", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatNodesResp represents the returned struct of the /_cat/nodes response +type CatNodesResp struct { + Nodes []CatNodesItemResp + response *opensearch.Response +} + +// CatNodesItemResp represents one index of the CatNodesResp +type CatNodesItemResp struct { + ID string `json:"id"` + PID string `json:"pid"` + IP string `json:"ip"` + Port int `json:"port,string"` + HTTPAddress string `json:"http_address"` + Version string `json:"version"` + Type string `json:"type"` + Build string `json:"build"` + JDK string `json:"jdk"` + DiskTotal string `json:"disk.total"` + DiskUsed string `json:"disk.used"` + DiskAvail string `json:"disk.avail"` + DiskUsedPercent string `json:"disk.used_percent"` + HeapCurrent string `json:"heap.current"` + HeapPercent int `json:"heap.percent,string"` + HeapMax string `json:"heap.max"` + RAMCurrent string `json:"ram.current"` + RAMPercent int `json:"ram.percent,string"` + RAMMax string `json:"ram.max"` + FileDescCurrent int `json:"file_desc.current,string"` + FileDescPercent int `json:"file_desc.percent,string"` + FileDescMax int `json:"file_desc.max,string"` + CPU int `json:"cpu,string"` + Load1M string `json:"load_1m"` + Load5M string `json:"load_5m"` + Load15M string `json:"load_15m"` + Uptime string `json:"uptime"` + Role string `json:"node.role"` + Roles string `json:"node.roles"` + Master string `json:"master"` + ClusterManager string `json:"cluster_manager"` + Name string `json:"name"` + CompletionSize string `json:"completion.size"` + FieldDataMemorySize string `json:"fielddata.memory_size"` + FileldDataEvictions int `json:"fielddata.evictions,string"` + QueryCacheMemorySize string `json:"query_cache.memory_size"` + QueryCacheEvictions int `json:"query_cache.evictions,string"` + QueryCacheHitCount int `json:"query_cache.hit_count,string"` + QueryCacheMissCount int `json:"query_cache.miss_count,string"` + RequestCacheMemorySize string `json:"request_cache.memory_size"` + RequestCacheEvictions int `json:"request_cache.evictions,string"` + RequestCacheHitCount int `json:"request_cache.hit_count,string"` + RequestCacheMissCount int `json:"request_cache.miss_count,string"` + FlushTotal int `json:"flush.total,string"` + FlushTotalTime string `json:"flush.total_time"` + GetCurrent int `json:"get.current,string"` + GetTime string `json:"get.time"` + GetTotal int `json:"get.total,string"` + GetExistsTime string `json:"get.exists_time"` + GetExistsTotal int `json:"get.exists_total,string"` + GetMissingTime string `json:"get.missing_time"` + GetMissingTotal int `json:"get.missing_total,string"` + IndexingDeleteCurrent int `json:"indexing.delete_current,string"` + IndexingDeleteTime string `json:"indexing.delete_time"` + IndexingDeleteTotal int `json:"indexing.delete_total,string"` + IndexingIndexCurrent int `json:"indexing.index_current,string"` + IndexingIndexTime string `json:"indexing.index_time"` + IndexingIndexTotal int `json:"indexing.index_total,string"` + IndexingIndexFailed int `json:"indexing.index_failed,string"` + MergesCurrent int `json:"merges.current,string"` + MergesCurrentDoc int `json:"merges.current_docs,string"` + MergesCurrentSize string `json:"merges.current_size"` + MergesTotal int `json:"merges.total,string"` + MergesTotalDocs int `json:"merges.total_docs,string"` + MergesTotalSize string `json:"merges.total_size"` + MergesTotalTime string `json:"merges.total_time"` + RefreshTotal int `json:"refresh.total,string"` + RefreshTime string `json:"refresh.time"` + RefreshExternalTotal int `json:"refresh.external_total,string"` + RefreshExternalTime string `json:"refresh.external_time"` + RefreshListeners int `json:"refresh.listeners,string"` + ScriptCompilations int `json:"script.compilations,string"` + ScriptCacheEvictions int `json:"script.cache_evictions,string"` + ScriptCompilationLimitTriggered int `json:"script.compilation_limit_triggered,string"` + SearchFetchCurrent int `json:"search.fetch_current,string"` + SearchFetchTime string `json:"search.fetch_time"` + SearchFetchTotal int `json:"search.fetch_total,string"` + SearchOpenContexts int `json:"search.open_contexts,string"` + SearchQueryCurrent int `json:"search.query_current,string"` + SearchQueryTime string `json:"search.query_time"` + SearchQueryTotal int `json:"search.query_total,string"` + SearchScrollCurrent int `json:"search.scroll_current,string"` + SearchScrollTime string `json:"search.scroll_time"` + SearchScrollTotal int `json:"search.scroll_total,string"` + SearchPointInTimeCurrent int `json:"search.point_in_time_current,string"` + SearchPointInTimeTime string `json:"search.point_in_time_time"` + SearchPointInTimeTotal int `json:"search.point_in_time_total,string"` + SegmentsCount int `json:"segments.count,string"` + SegmentsMemory string `json:"segments.memory"` + SegmentsIndexWriteMemory string `json:"segments.index_writer_memory"` + SegmentsVersionMapMemory string `json:"segments.version_map_memory"` + SegmentsFixedBitsetMemory string `json:"segments.fixed_bitset_memory"` + SuggestCurrent int `json:"suggest.current,string"` + SuggestTime string `json:"suggest.time"` + SuggestTotal int `json:"suggest.total,string"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatNodesResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-pending_tasks-params.go b/opensearchapi/api_cat-pending_tasks-params.go new file mode 100644 index 000000000..c9b07a64e --- /dev/null +++ b/opensearchapi/api_cat-pending_tasks-params.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatPendingTasksParams represents possible parameters for the CatPendingTasksReq +type CatPendingTasksParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatPendingTasksParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-pending_tasks.go b/opensearchapi/api_cat-pending_tasks.go new file mode 100644 index 000000000..98e278353 --- /dev/null +++ b/opensearchapi/api_cat-pending_tasks.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatPendingTasksReq represent possible options for the /_cat/pending_tasks request +type CatPendingTasksReq struct { + Header http.Header + Params CatPendingTasksParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatPendingTasksReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/pending_tasks", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatPendingTasksResp represents the returned struct of the /_cat/pending_tasks response +type CatPendingTasksResp struct { + PendingTasks []CatPendingTaskResp + response *opensearch.Response +} + +// CatPendingTaskResp represents one index of the CatPendingTasksResp +type CatPendingTaskResp struct { + InsertOrder string `json:"insertOrder"` + TimeInQueue string `json:"timeInQueue"` + Priority string `json:"priority"` + Source string `json:"source"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatPendingTasksResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-plugins-params.go b/opensearchapi/api_cat-plugins-params.go new file mode 100644 index 000000000..03670a052 --- /dev/null +++ b/opensearchapi/api_cat-plugins-params.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatPluginsParams represents possible parameters for the CatPluginsReq +type CatPluginsParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatPluginsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-plugins.go b/opensearchapi/api_cat-plugins.go new file mode 100644 index 000000000..65480a92f --- /dev/null +++ b/opensearchapi/api_cat-plugins.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatPluginsReq represent possible options for the /_cat/plugins request +type CatPluginsReq struct { + Header http.Header + Params CatPluginsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatPluginsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/plugins", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatPluginsResp represents the returned struct of the /_cat/plugins response +type CatPluginsResp struct { + Plugins []CatPluginResp + response *opensearch.Response +} + +// CatPluginResp represents one index of the CatPluginsResp +type CatPluginResp struct { + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Component string `json:"component,omitempty"` + Version string `json:"version,omitempty"` + Description string `json:"description,omitempty"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatPluginsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-recovery-params.go b/opensearchapi/api_cat-recovery-params.go new file mode 100644 index 000000000..c343c010a --- /dev/null +++ b/opensearchapi/api_cat-recovery-params.go @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatRecoveryParams represents possible parameters for the CatRecoveryReq +type CatRecoveryParams struct { + ActiveOnly *bool + Bytes string + Detailed *bool + H []string + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatRecoveryParams) get() map[string]string { + params := make(map[string]string) + + if r.ActiveOnly != nil { + params["active_only"] = strconv.FormatBool(*r.ActiveOnly) + } + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if r.Detailed != nil { + params["detailed"] = strconv.FormatBool(*r.Detailed) + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-recovery.go b/opensearchapi/api_cat-recovery.go new file mode 100644 index 000000000..2d270f6bb --- /dev/null +++ b/opensearchapi/api_cat-recovery.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatRecoveryReq represent possible options for the /_cat/recovery request +type CatRecoveryReq struct { + Indices []string + Header http.Header + Params CatRecoveryParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatRecoveryReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("/_cat/recovery/") + len(indices)) + path.WriteString("/_cat/recovery") + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatRecoveryResp represents the returned struct of the /_cat/recovery response +type CatRecoveryResp struct { + Recovery []CatRecoveryItemResp + response *opensearch.Response +} + +// CatRecoveryItemResp represents one index of the CatRecoveryResp +type CatRecoveryItemResp struct { + Index string `json:"index"` + Shard int `json:"shard,string"` + StartTime string `json:"start_time"` + StartTimeMillis int `json:"start_time_millis,string"` + StopTime string `json:"stop_time"` + StopTimeMillis int `json:"stop_time_millis,string"` + Time string `json:"time"` + Type string `json:"type"` + Stage string `json:"stage"` + SourceHost string `json:"source_host"` + SourceNode string `json:"source_node"` + TargetHost string `json:"target_host"` + TargetNode string `json:"target_node"` + Repository string `json:"repository"` + Snapshot string `json:"snapshot"` + Files int `json:"files,string"` + FilesRecovered int `json:"files_recovered,string"` + FilesPercent string `json:"files_percent"` + FilesTotal int `json:"files_total,string"` + Bytes int `json:"bytes,string"` + BytesRecovered int `json:"bytes_recovered,string"` + BytesPercent string `json:"bytes_percent"` + BytesTotal int `json:"bytes_total,string"` + TranslogOps int `json:"translog_ops,string"` + TranslogOpsRecovered int `json:"translog_ops_recovered,string"` + TranslogOpsPercent string `json:"translog_ops_percent"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatRecoveryResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-repositories-params.go b/opensearchapi/api_cat-repositories-params.go new file mode 100644 index 000000000..ab193d935 --- /dev/null +++ b/opensearchapi/api_cat-repositories-params.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatRepositoriesParams represents possible parameters for the CatRepositoriesReq +type CatRepositoriesParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatRepositoriesParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-repositories.go b/opensearchapi/api_cat-repositories.go new file mode 100644 index 000000000..7f6b20a72 --- /dev/null +++ b/opensearchapi/api_cat-repositories.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatRepositoriesReq represent possible options for the /_cat/repositories request +type CatRepositoriesReq struct { + Header http.Header + Params CatRepositoriesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatRepositoriesReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/repositories", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatRepositoriesResp represents the returned struct of the /_cat/repositories response +type CatRepositoriesResp struct { + Repositories []CatRepositorieResp + response *opensearch.Response +} + +// CatRepositorieResp represents one index of the CatRepositoriesResp +type CatRepositorieResp struct { + ID string `json:"id"` + Type string `json:"type"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatRepositoriesResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-segments-params.go b/opensearchapi/api_cat-segments-params.go new file mode 100644 index 000000000..daf2df8a2 --- /dev/null +++ b/opensearchapi/api_cat-segments-params.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatSegmentsParams represents possible parameters for the CatSegmentsReq +type CatSegmentsParams struct { + Bytes string + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatSegmentsParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-segments.go b/opensearchapi/api_cat-segments.go new file mode 100644 index 000000000..c51e81a2d --- /dev/null +++ b/opensearchapi/api_cat-segments.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatSegmentsReq represent possible options for the /_cat/segments request +type CatSegmentsReq struct { + Indices []string + Header http.Header + Params CatSegmentsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatSegmentsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("/_cat/segments/") + len(indices)) + path.WriteString("/_cat/segments") + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatSegmentsResp represents the returned struct of the /_cat/segments response +type CatSegmentsResp struct { + Segments []CatSegmentResp + response *opensearch.Response +} + +// CatSegmentResp represents one index of the CatSegmentsResp +type CatSegmentResp struct { + Index string `json:"index"` + Shard int `json:"shard,string"` + Prirep string `json:"prirep"` + IP string `json:"ip"` + ID string `json:"id"` + Segment string `json:"segment"` + Generation int `json:"generation,string"` + DocsCount int `json:"docs.count,string"` + DocsDeleted int `json:"docs.deleted,string"` + Size string `json:"size"` + SizeMemory string `json:"size.memory"` + Committed bool `json:"committed,string"` + Searchable bool `json:"searchable,string"` + Version string `json:"version"` + Compound bool `json:"compound,string"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatSegmentsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-shards-params.go b/opensearchapi/api_cat-shards-params.go new file mode 100644 index 000000000..ea29be4d1 --- /dev/null +++ b/opensearchapi/api_cat-shards-params.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatShardsParams represents possible parameters for the CatShardsReq +type CatShardsParams struct { + Bytes string + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatShardsParams) get() map[string]string { + params := make(map[string]string) + + if r.Bytes != "" { + params["bytes"] = r.Bytes + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-shards.go b/opensearchapi/api_cat-shards.go new file mode 100644 index 000000000..b9a91d843 --- /dev/null +++ b/opensearchapi/api_cat-shards.go @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatShardsReq represent possible options for the /_cat/shards request +type CatShardsReq struct { + Indices []string + Header http.Header + Params CatShardsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatShardsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("/_cat/shards/") + len(indices)) + path.WriteString("/_cat/shards") + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatShardsResp represents the returned struct of the /_cat/shards response +type CatShardsResp struct { + Shards []CatShardResp + response *opensearch.Response +} + +// CatShardResp represents one index of the CatShardsResp +type CatShardResp struct { + Index string `json:"index"` + Shard int `json:"shard,string"` + Prirep string `json:"prirep"` + State string `json:"state"` + Docs *string `json:"docs"` + Store *string `json:"store"` + IP *string `json:"ip"` + ID *string `json:"id"` + Node *string `json:"node"` + SyncID *string `json:"sync_id"` + UnassignedReason *string `json:"unassigned.reason"` + UnassignedAt *string `json:"unassigned.at"` + UnassignedFor *string `json:"unassigned.for"` + UnassignedDetails *string `json:"unassigned.details"` + RecoverysourceType *string `json:"recoverysource.type"` + CompletionSize *string `json:"completion.size"` + FielddataMemorySize *string `json:"fielddata.memory_size"` + FielddataEvictions *int `json:"fielddata.evictions,string"` + QueryCacheMemorySize *string `json:"query_cache.memory_size"` + QueryCacheEvictions *int `json:"query_cache.evictions,string"` + FlushTotal *int `json:"flush.total,string"` + FlushTotalTime *string `json:"flush.total_time"` + GetCurrent *int `json:"get.current,string"` + GetTime *string `json:"get.time"` + GetTotal *int `json:"get.total,string"` + GetExistsTime *string `json:"get.exists_time"` + GetExistsTotal *int `json:"get.exists_total,string"` + GetMissingTime *string `json:"get.missing_time"` + GetMissingTotal *int `json:"get.missing_total,string"` + IndexingDeleteCurrent *int `json:"indexing.delete_current,string"` + IndexingDeleteTime *string `json:"indexing.delete_time"` + IndexingDeleteTotal *string `json:"indexing.delete_total"` + IndexingIndexCurrent *int `json:"indexing.index_current,string"` + IndexingIndexTime *string `json:"indexing.index_time"` + IndexingIndexTotal *int `json:"indexing.index_total,string"` + IndexingIndexFailed *int `json:"indexing.index_failed,string"` + MergesCurrent *int `json:"merges.current,string"` + MergesCurrentDocs *int `json:"merges.current_docs,string"` + MergesCurrentSize *string `json:"merges.current_size"` + MergesTotal *int `json:"merges.total,string"` + MergesTotalDocs *int `json:"merges.total_docs,string"` + MergesTotalSize *string `json:"merges.total_size"` + MergesTotalTime *string `json:"merges.total_time"` + RefreshTotal *int `json:"refresh.total,string"` + RefreshTime *string `json:"refresh.time"` + RefreshExternalTotal *int `json:"refresh.external_total,string"` + RefreshExternalTime *string `json:"refresh.external_time"` + RefreshListeners *int `json:"refresh.listeners,string"` + SearchFetchCurrent *int `json:"search.fetch_current,string"` + SearchFetchTime *string `json:"search.fetch_time"` + SearchFetchTotal *int `json:"search.fetch_total,string"` + SearchOpenContexts *int `json:"search.open_contexts,string"` + SearchQueryCurrent *int `json:"search.query_current,string"` + SearchQueryTime *string `json:"search.query_time"` + SearchQueryTotal *int `json:"search.query_total,string"` + SearchScrollCurrent *int `json:"search.scroll_current,string"` + SearchScrollTime *string `json:"search.scroll_time"` + SearchScrollTotal *int `json:"search.scroll_total,string"` + SearchPointInTimeCurrent *int `json:"search.point_in_time_current,string"` + SearchPointInTimeTime *string `json:"search.point_in_time_time"` + SearchPointInTimeTotal *int `json:"search.point_in_time_total,string"` + SegmentsCount *int `json:"segments.count,string"` + SegmentsMemory *string `json:"segments.memory"` + SegmentsIndexWriterMemory *string `json:"segments.index_writer_memory"` + SegmentsVersionMapMemory *string `json:"segments.version_map_memory"` + SegmentsFixedBitsetMemory *string `json:"segments.fixed_bitset_memory"` + SeqNoMax *int `json:"seq_no.max,string"` + SeqNoLocalCheckpoint *int `json:"seq_no.local_checkpoint,string"` + SeqNoGlobalCheckpoint *int `json:"seq_no.global_checkpoint,string"` + WarmerCurrent *int `json:"warmer.current,string"` + WarmerTotal *int `json:"warmer.total,string"` + WarmerTotalTime *string `json:"warmer.total_time"` + PathData *string `json:"path.data"` + PathState *string `json:"path.state"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatShardsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-snapshots-params.go b/opensearchapi/api_cat-snapshots-params.go new file mode 100644 index 000000000..16cec68ae --- /dev/null +++ b/opensearchapi/api_cat-snapshots-params.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatSnapshotsParams represents possible parameters for the CatSnapshotsReq +type CatSnapshotsParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatSnapshotsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-snapshots.go b/opensearchapi/api_cat-snapshots.go new file mode 100644 index 000000000..166365817 --- /dev/null +++ b/opensearchapi/api_cat-snapshots.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatSnapshotsReq represent possible options for the /_cat/snapshots request +type CatSnapshotsReq struct { + Repository string + Header http.Header + Params CatSnapshotsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatSnapshotsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("%s%s", "/_cat/snapshots/", r.Repository), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatSnapshotsResp represents the returned struct of the /_cat/snapshots response +type CatSnapshotsResp struct { + Snapshots []CatSnapshotResp + response *opensearch.Response +} + +// CatSnapshotResp represents one index of the CatSnapshotsResp +type CatSnapshotResp struct { + ID string `json:"id"` + Status string `json:"status"` + StartEpoch int `json:"start_epoch,string"` + StartTime string `json:"start_time"` + EndEpoch int `json:"end_epoch,string"` + EndTime string `json:"end_time"` + Duration string `json:"duration"` + Indices int `json:"indices,string"` + SuccessfulShards int `json:"successful_shards,string"` + FailedShards int `json:"failed_shards,string"` + TotalShards int `json:"total_shards,string"` + Reason string `json:"reason"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatSnapshotsResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-tasks-params.go b/opensearchapi/api_cat-tasks-params.go new file mode 100644 index 000000000..c120d18a6 --- /dev/null +++ b/opensearchapi/api_cat-tasks-params.go @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// CatTasksParams represents possible parameters for the CatTasksReq +type CatTasksParams struct { + Actions []string + Detailed *bool + H []string + Nodes []string + ParentTaskID string + Local *bool + Sort []string + Time string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatTasksParams) get() map[string]string { + params := make(map[string]string) + + if len(r.Actions) > 0 { + params["actions"] = strings.Join(r.Actions, ",") + } + + if r.Detailed != nil { + params["detailed"] = strconv.FormatBool(*r.Detailed) + } + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if len(r.Nodes) > 0 { + params["nodes"] = strings.Join(r.Nodes, ",") + } + + if r.ParentTaskID != "" { + params["parent_task_id"] = r.ParentTaskID + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.Time != "" { + params["time"] = r.Time + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-tasks.go b/opensearchapi/api_cat-tasks.go new file mode 100644 index 000000000..af67668ba --- /dev/null +++ b/opensearchapi/api_cat-tasks.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatTasksReq represent possible options for the /_cat/tasks request +type CatTasksReq struct { + Header http.Header + Params CatTasksParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatTasksReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cat/tasks", + nil, + r.Params.get(), + r.Header, + ) +} + +// CatTasksResp represents the returned struct of the /_cat/tasks response +type CatTasksResp struct { + Tasks []CatTaskResp + response *opensearch.Response +} + +// CatTaskResp represents one index of the CatTasksResp +type CatTaskResp struct { + ID string `json:"id"` + Action string `json:"action"` + TaskID string `json:"task_id"` + ParentTaskID string `json:"parent_task_id"` + Type string `json:"type"` + StartTime int `json:"start_time,string"` + Timestamp string `json:"timestamp"` + RunningTimeNs int `json:"running_time_ns,string"` + RunningTime string `json:"running_time"` + NodeID string `json:"node_id"` + IP string `json:"ip"` + Port int `json:"port,string"` + Node string `json:"node"` + Version string `json:"version"` + XOpaqueID string `json:"x_opaque_id"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatTasksResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-templates-params.go b/opensearchapi/api_cat-templates-params.go new file mode 100644 index 000000000..71a028742 --- /dev/null +++ b/opensearchapi/api_cat-templates-params.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatTemplatesParams represents possible parameters for the CatTemplatesReq +type CatTemplatesParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatTemplatesParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-templates.go b/opensearchapi/api_cat-templates.go new file mode 100644 index 000000000..60fcf2844 --- /dev/null +++ b/opensearchapi/api_cat-templates.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatTemplatesReq represent possible options for the /_cat/templates request +type CatTemplatesReq struct { + Templates []string + Header http.Header + Params CatTemplatesParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatTemplatesReq) GetRequest() (*http.Request, error) { + templates := strings.Join(r.Templates, ",") + var path strings.Builder + path.Grow(len("/_cat/templates/") + len(templates)) + path.WriteString("/_cat/templates") + if len(r.Templates) > 0 { + path.WriteString("/") + path.WriteString(templates) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatTemplatesResp represents the returned struct of the /_cat/templates response +type CatTemplatesResp struct { + Templates []CatTemplateResp + response *opensearch.Response +} + +// CatTemplateResp represents one index of the CatTemplatesResp +type CatTemplateResp struct { + Name string `json:"name"` + IndexPatterns string `json:"index_patterns"` + Order int `json:"order,string"` + Version *string `json:"version"` + ComposedOf string `json:"composed_of"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatTemplatesResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat-thread_pool-params.go b/opensearchapi/api_cat-thread_pool-params.go new file mode 100644 index 000000000..b84c961f7 --- /dev/null +++ b/opensearchapi/api_cat-thread_pool-params.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// CatThreadPoolParams represents possible parameters for the CatThreadPoolReq +type CatThreadPoolParams struct { + H []string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Sort []string + V *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r CatThreadPoolParams) get() map[string]string { + params := make(map[string]string) + + if len(r.H) > 0 { + params["h"] = strings.Join(r.H, ",") + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Sort) > 0 { + params["s"] = strings.Join(r.Sort, ",") + } + + if r.V != nil { + params["v"] = strconv.FormatBool(*r.V) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + params["format"] = "json" + + return params +} diff --git a/opensearchapi/api_cat-thread_pool.go b/opensearchapi/api_cat-thread_pool.go new file mode 100644 index 000000000..48a1ede55 --- /dev/null +++ b/opensearchapi/api_cat-thread_pool.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// CatThreadPoolReq represent possible options for the /_cat/thread_pool request +type CatThreadPoolReq struct { + Pools []string + Header http.Header + Params CatThreadPoolParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r CatThreadPoolReq) GetRequest() (*http.Request, error) { + pools := strings.Join(r.Pools, ",") + var path strings.Builder + path.Grow(len("/_cat/thread_pool/") + len(pools)) + path.WriteString("/_cat/thread_pool") + if len(r.Pools) > 0 { + path.WriteString("/") + path.WriteString(pools) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// CatThreadPoolResp represents the returned struct of the /_cat/thread_pool response +type CatThreadPoolResp struct { + ThreadPool []CatThreadPoolItemResp + response *opensearch.Response +} + +// CatThreadPoolItemResp represents one index of the CatThreadPoolResp +type CatThreadPoolItemResp struct { + NodeName string `json:"node_name"` + NodeID string `json:"node_id"` + EphemeralNodeID string `json:"ephemeral_node_id"` + PID int `json:"pid,string"` + Host string `json:"host"` + IP string `json:"ip"` + Port int `json:"port,string"` + Name string `json:"name"` + Type string `json:"type"` + Active int `json:"active,string"` + PoolSize int `json:"pool_size,string"` + Queue int `json:"queue,string"` + QueueSize int `json:"queue_size,string"` + Rejected int `json:"rejected,string"` + Largest int `json:"largest,string"` + Completed int `json:"completed,string"` + Core *int `json:"core,string"` + Max *int `json:"max,string"` + Size *int `json:"size,string"` + KeepAlive *string `json:"keep_alive"` + TotalWaitTime string `json:"total_wait_time"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r CatThreadPoolResp) Inspect() Inspect { + return Inspect{ + Response: r.response, + } +} diff --git a/opensearchapi/api_cat.go b/opensearchapi/api_cat.go new file mode 100644 index 000000000..7ddd0f4aa --- /dev/null +++ b/opensearchapi/api_cat.go @@ -0,0 +1,351 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type catClient struct { + apiClient *Client +} + +// Aliases executes a /_cat/aliases request with the optional CatAliasesReq +func (c catClient) Aliases(ctx context.Context, req *CatAliasesReq) (*CatAliasesResp, error) { + if req == nil { + req = &CatAliasesReq{} + } + + var ( + data CatAliasesResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Aliases); err != nil { + return &data, err + } + + return &data, nil +} + +// Allocation executes a /_cat/allocation request with the optional CatAllocationReq +func (c catClient) Allocation(ctx context.Context, req *CatAllocationReq) (*CatAllocationsResp, error) { + if req == nil { + req = &CatAllocationReq{} + } + + var ( + data CatAllocationsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Allocations); err != nil { + return &data, err + } + + return &data, nil +} + +// ClusterManager executes a /_cat/cluster_manager request with the optional CatClusterManagerReq +func (c catClient) ClusterManager(ctx context.Context, req *CatClusterManagerReq) (*CatClusterManagersResp, error) { + if req == nil { + req = &CatClusterManagerReq{} + } + + var ( + data CatClusterManagersResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.ClusterManagers); err != nil { + return &data, err + } + + return &data, nil +} + +// Count executes a /_cat/count request with the optional CatCountReq +func (c catClient) Count(ctx context.Context, req *CatCountReq) (*CatCountsResp, error) { + if req == nil { + req = &CatCountReq{} + } + + var ( + data CatCountsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Counts); err != nil { + return &data, err + } + + return &data, nil +} + +// FieldData executes a /_cat/fielddata request with the optional CatFieldDataReq +func (c catClient) FieldData(ctx context.Context, req *CatFieldDataReq) (*CatFieldDataResp, error) { + if req == nil { + req = &CatFieldDataReq{} + } + + var ( + data CatFieldDataResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.FieldData); err != nil { + return &data, err + } + + return &data, nil +} + +// Health executes a /_cat/health request with the optional CatHealthReq +func (c catClient) Health(ctx context.Context, req *CatHealthReq) (*CatHealthResp, error) { + if req == nil { + req = &CatHealthReq{} + } + + var ( + data CatHealthResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Health); err != nil { + return &data, err + } + + return &data, nil +} + +// Indices executes a /_cat/indices request with the optional CatIndicesReq +func (c catClient) Indices(ctx context.Context, req *CatIndicesReq) (*CatIndicesResp, error) { + if req == nil { + req = &CatIndicesReq{} + } + + var ( + data CatIndicesResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Master executes a /_cat/master request with the optional CatMasterReq +func (c catClient) Master(ctx context.Context, req *CatMasterReq) (*CatMasterResp, error) { + if req == nil { + req = &CatMasterReq{} + } + + var ( + data CatMasterResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Master); err != nil { + return &data, err + } + + return &data, nil +} + +// NodeAttrs executes a /_cat/nodeattrs request with the optional CatNodeAttrsReq +func (c catClient) NodeAttrs(ctx context.Context, req *CatNodeAttrsReq) (*CatNodeAttrsResp, error) { + if req == nil { + req = &CatNodeAttrsReq{} + } + + var ( + data CatNodeAttrsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.NodeAttrs); err != nil { + return &data, err + } + + return &data, nil +} + +// Nodes executes a /_cat/nodes request with the optional CatNodesReq +func (c catClient) Nodes(ctx context.Context, req *CatNodesReq) (*CatNodesResp, error) { + if req == nil { + req = &CatNodesReq{} + } + + var ( + data CatNodesResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Nodes); err != nil { + return &data, err + } + + return &data, nil +} + +// PendingTasks executes a /_cat/pending_tasks request with the optional CatPendingTasksReq +func (c catClient) PendingTasks(ctx context.Context, req *CatPendingTasksReq) (*CatPendingTasksResp, error) { + if req == nil { + req = &CatPendingTasksReq{} + } + + var ( + data CatPendingTasksResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.PendingTasks); err != nil { + return &data, err + } + + return &data, nil +} + +// Plugins executes a /_cat/plugins request with the optional CatPluginsReq +func (c catClient) Plugins(ctx context.Context, req *CatPluginsReq) (*CatPluginsResp, error) { + if req == nil { + req = &CatPluginsReq{} + } + + var ( + data CatPluginsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Plugins); err != nil { + return &data, err + } + + return &data, nil +} + +// Recovery executes a /_cat/recovery request with the optional CatRecoveryReq +func (c catClient) Recovery(ctx context.Context, req *CatRecoveryReq) (*CatRecoveryResp, error) { + if req == nil { + req = &CatRecoveryReq{} + } + + var ( + data CatRecoveryResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Recovery); err != nil { + return &data, err + } + + return &data, nil +} + +// Repositories executes a /_cat/repositories request with the optional CatRepositoriesReq +func (c catClient) Repositories(ctx context.Context, req *CatRepositoriesReq) (*CatRepositoriesResp, error) { + if req == nil { + req = &CatRepositoriesReq{} + } + + var ( + data CatRepositoriesResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Repositories); err != nil { + return &data, err + } + + return &data, nil +} + +// Segments executes a /_cat/segments request with the optional CatSegmentsReq +func (c catClient) Segments(ctx context.Context, req *CatSegmentsReq) (*CatSegmentsResp, error) { + if req == nil { + req = &CatSegmentsReq{} + } + + var ( + data CatSegmentsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Segments); err != nil { + return &data, err + } + + return &data, nil +} + +// Shards executes a /_cat/shards request with the optional CatShardsReq +func (c catClient) Shards(ctx context.Context, req *CatShardsReq) (*CatShardsResp, error) { + if req == nil { + req = &CatShardsReq{} + } + + var ( + data CatShardsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Shards); err != nil { + return &data, err + } + + return &data, nil +} + +// Snapshots executes a /_cat/snapshots request with the required CatSnapshotsReq +func (c catClient) Snapshots(ctx context.Context, req CatSnapshotsReq) (*CatSnapshotsResp, error) { + var ( + data CatSnapshotsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Snapshots); err != nil { + return &data, err + } + + return &data, nil +} + +// Tasks executes a /_cat/tasks request with the optional CatTasksReq +func (c catClient) Tasks(ctx context.Context, req *CatTasksReq) (*CatTasksResp, error) { + if req == nil { + req = &CatTasksReq{} + } + + var ( + data CatTasksResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Tasks); err != nil { + return &data, err + } + + return &data, nil +} + +// Templates executes a /_cat/templates request with the optional CatTemplatesReq +func (c catClient) Templates(ctx context.Context, req *CatTemplatesReq) (*CatTemplatesResp, error) { + if req == nil { + req = &CatTemplatesReq{} + } + + var ( + data CatTemplatesResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Templates); err != nil { + return &data, err + } + + return &data, nil +} + +// ThreadPool executes a /_cat/thread_pool request with the optional CatThreadPoolReq +func (c catClient) ThreadPool(ctx context.Context, req *CatThreadPoolReq) (*CatThreadPoolResp, error) { + if req == nil { + req = &CatThreadPoolReq{} + } + + var ( + data CatThreadPoolResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.ThreadPool); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_cat_test.go b/opensearchapi/api_cat_test.go new file mode 100644 index 000000000..bb8d90bb5 --- /dev/null +++ b/opensearchapi/api_cat_test.go @@ -0,0 +1,512 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestCatClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + // snapshotRepo := "test-snapshot-repo" + + index := "test-cat-indices" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{index}}) + }) + + _, err = client.Indices.Create(nil, opensearchapi.IndicesCreateReq{Index: index, Body: strings.NewReader(`{"aliases":{"TEST_CAT_ALIAS":{}}}`)}) + require.Nil(t, err) + + type catTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := map[string][]catTests{ + "Aliases": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Aliases(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Aliases(nil, &opensearchapi.CatAliasesReq{Aliases: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Aliases(nil, nil) }, + }, + }, + "Allocation": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Allocation(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Allocation(nil, &opensearchapi.CatAllocationReq{NodeIDs: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Allocation(nil, nil) }, + }, + }, + "ClusterManager": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.ClusterManager(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.ClusterManager(nil, &opensearchapi.CatClusterManagerReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.ClusterManager(nil, nil) }, + }, + }, + "Count": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Count(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Count(nil, &opensearchapi.CatCountReq{Indices: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Count(nil, nil) }, + }, + }, + "FieldData": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.FieldData(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.FieldData(nil, &opensearchapi.CatFieldDataReq{FieldData: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.FieldData(nil, nil) }, + }, + }, + "Health": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Health(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Health(nil, &opensearchapi.CatHealthReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Health(nil, nil) }, + }, + }, + "Indices": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Indices(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Indices(nil, &opensearchapi.CatIndicesReq{Indices: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Indices(nil, nil) }, + }, + }, + "Master": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Master(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Master(nil, &opensearchapi.CatMasterReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Master(nil, nil) }, + }, + }, + "NodeAttrs": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.NodeAttrs(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.NodeAttrs(nil, &opensearchapi.CatNodeAttrsReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.NodeAttrs(nil, nil) }, + }, + }, + "Nodes": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Nodes(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Nodes(nil, &opensearchapi.CatNodesReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Nodes(nil, nil) }, + }, + }, + "PendingTasks": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.PendingTasks(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.PendingTasks(nil, &opensearchapi.CatPendingTasksReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.PendingTasks(nil, nil) }, + }, + }, + "Plugins": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Plugins(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Plugins(nil, &opensearchapi.CatPluginsReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Plugins(nil, nil) }, + }, + }, + "Recovery": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Recovery(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Recovery(nil, &opensearchapi.CatRecoveryReq{Indices: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Recovery(nil, nil) }, + }, + }, + "Repositories": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Repositories(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Repositories(nil, &opensearchapi.CatRepositoriesReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Repositories(nil, nil) }, + }, + }, + "Segments": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Segments(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Segments(nil, &opensearchapi.CatSegmentsReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Segments(nil, nil) }, + }, + }, + "Shards": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Shards(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Shards(nil, &opensearchapi.CatShardsReq{Indices: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Shards(nil, nil) }, + }, + }, + /* Need to create snapshot + repo + "Shards": []catTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Snapshots(nil, opensearchapi.CatSnapshotsReq{Repository: snapshotRepo}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Cat.Snapshots(nil, opensearchapi.CatSnapshotsReq{Repository: snapshotRepo}) + }, + }, + }, + */ + "Tasks": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Tasks(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Tasks(nil, &opensearchapi.CatTasksReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Tasks(nil, nil) }, + }, + }, + "Templates": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.Templates(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.Templates(nil, &opensearchapi.CatTemplatesReq{Templates: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.Templates(nil, nil) }, + }, + }, + "ThreadPool": []catTests{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cat.ThreadPool(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cat.ThreadPool(nil, &opensearchapi.CatThreadPoolReq{Pools: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cat.ThreadPool(nil, nil) }, + }, + }, + } + for catType, value := range testCases { + t.Run(catType, func(t *testing.T) { + if catType == "ClusterManager" { + osapitest.SkipIfBelowVersion(t, client, 1, 3, catType) + } + for _, testCase := range value { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + assert.Nil(t, err) + assert.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + } + }) + } + }) + } + + t.Run("ValidateResponse", func(t *testing.T) { + t.Run("Aliases", func(t *testing.T) { + resp, err := client.Cat.Aliases(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Aliases, resp.Inspect().Response) + }) + t.Run("Allocation", func(t *testing.T) { + resp, err := client.Cat.Allocation(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Allocations, resp.Inspect().Response) + }) + t.Run("ClusterManager", func(t *testing.T) { + osapitest.SkipIfBelowVersion(t, client, 1, 3, "ClusterManager") + resp, err := client.Cat.ClusterManager(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.ClusterManagers, resp.Inspect().Response) + }) + t.Run("Count", func(t *testing.T) { + resp, err := client.Cat.Count(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Counts, resp.Inspect().Response) + }) + t.Run("FieldData", func(t *testing.T) { + resp, err := client.Cat.FieldData(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.FieldData, resp.Inspect().Response) + }) + t.Run("Health", func(t *testing.T) { + resp, err := client.Cat.Health(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Health, resp.Inspect().Response) + }) + t.Run("Indices", func(t *testing.T) { + resp, err := client.Cat.Indices(nil, &opensearchapi.CatIndicesReq{Params: opensearchapi.CatIndicesParams{H: []string{"*"}}}) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Indices, resp.Inspect().Response) + }) + t.Run("Master", func(t *testing.T) { + resp, err := client.Cat.Master(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Master, resp.Inspect().Response) + }) + t.Run("NodeAttrs", func(t *testing.T) { + resp, err := client.Cat.NodeAttrs(nil, &opensearchapi.CatNodeAttrsReq{Params: opensearchapi.CatNodeAttrsParams{H: []string{"*"}}}) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.NodeAttrs, resp.Inspect().Response) + }) + t.Run("Nodes", func(t *testing.T) { + resp, err := client.Cat.Nodes(nil, &opensearchapi.CatNodesReq{Params: opensearchapi.CatNodesParams{H: []string{"*"}}}) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Nodes, resp.Inspect().Response) + }) + t.Run("PendingTasks", func(t *testing.T) { + resp, err := client.Cat.PendingTasks(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.PendingTasks, resp.Inspect().Response) + }) + t.Run("Plugins", func(t *testing.T) { + resp, err := client.Cat.Plugins(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Plugins, resp.Inspect().Response) + }) + t.Run("Recovery", func(t *testing.T) { + resp, err := client.Cat.Recovery(nil, &opensearchapi.CatRecoveryReq{Params: opensearchapi.CatRecoveryParams{H: []string{"*"}}}) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Recovery, resp.Inspect().Response) + }) + t.Run("Repositories", func(t *testing.T) { + resp, err := client.Cat.Repositories(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Repositories, resp.Inspect().Response) + }) + t.Run("Segments", func(t *testing.T) { + resp, err := client.Cat.Segments(nil, &opensearchapi.CatSegmentsReq{Params: opensearchapi.CatSegmentsParams{H: []string{"*"}}}) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Segments, resp.Inspect().Response) + }) + t.Run("Shards", func(t *testing.T) { + resp, err := client.Cat.Shards(nil, &opensearchapi.CatShardsReq{Params: opensearchapi.CatShardsParams{H: []string{"*"}}}) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Shards, resp.Inspect().Response) + }) + /* Need to create Snapshot + Repo + t.Run("Snapshots", func(t *testing.T) { + resp, err := client.Cat.Snapshots(nil, &opensearchapi.CatSnapshotsReq{Repository: snapshotRepo, Params: opensearchapi.CatSnapshotsParams{H: []string{"*"}}}) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Snapshots, resp.Inspect().Response) + }) + */ + t.Run("Tasks", func(t *testing.T) { + resp, err := client.Cat.Tasks(nil, &opensearchapi.CatTasksReq{Params: opensearchapi.CatTasksParams{H: []string{"*"}}}) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Tasks, resp.Inspect().Response) + }) + t.Run("Templates", func(t *testing.T) { + resp, err := client.Cat.Templates(nil, nil) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Templates, resp.Inspect().Response) + }) + t.Run("ThreadPool", func(t *testing.T) { + resp, err := client.Cat.ThreadPool(nil, &opensearchapi.CatThreadPoolReq{Params: opensearchapi.CatThreadPoolParams{H: []string{"*"}}}) + assert.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.ThreadPool, resp.Inspect().Response) + }) + }) +} diff --git a/opensearchapi/api_cluster-allocation_explain-params.go b/opensearchapi/api_cluster-allocation_explain-params.go new file mode 100644 index 000000000..bd31edfdb --- /dev/null +++ b/opensearchapi/api_cluster-allocation_explain-params.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" +) + +// ClusterAllocationExplainParams represents possible parameters for the ClusterAllocationExplainReq +type ClusterAllocationExplainParams struct { + IncludeDiskInfo *bool + IncludeYesDecisions *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterAllocationExplainParams) get() map[string]string { + params := make(map[string]string) + + if r.IncludeDiskInfo != nil { + params["include_disk_info"] = strconv.FormatBool(*r.IncludeDiskInfo) + } + + if r.IncludeYesDecisions != nil { + params["include_yes_decisions"] = strconv.FormatBool(*r.IncludeYesDecisions) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_cluster-allocation_explain.go b/opensearchapi/api_cluster-allocation_explain.go new file mode 100644 index 000000000..e03f5a128 --- /dev/null +++ b/opensearchapi/api_cluster-allocation_explain.go @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ClusterAllocationExplainReq represents possible options for the /_nodes request +type ClusterAllocationExplainReq struct { + Body *ClusterAllocationExplainBody + Header http.Header + Params ClusterAllocationExplainParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterAllocationExplainReq) GetRequest() (*http.Request, error) { + var reader io.Reader + + if r.Body != nil { + body, err := json.Marshal(r.Body) + if err != nil { + return nil, err + } + + reader = bytes.NewReader(body) + } + + return opensearch.BuildRequest( + "GET", + "/_cluster/allocation/explain", + reader, + r.Params.get(), + r.Header, + ) +} + +// ClusterAllocationExplainBody represents the optional Body for the ClusterAllocationExplainReq +type ClusterAllocationExplainBody struct { + Index string `json:"index"` + Shard int `json:"shard"` + Primary bool `json:"primary"` +} + +// ClusterAllocationExplainResp represents the returned struct of the /_nodes response +type ClusterAllocationExplainResp struct { + Index string `json:"index"` + Shard int `json:"shard"` + Primary bool `json:"primary"` + CurrentState string `json:"current_state"` + CurrentNode ClusterAllocationCurrentNode `json:"current_node"` + UnassignedInfo struct { + Reason string `json:"reason"` + At string `json:"at"` + LastAllocationStatus string `json:"last_allocation_status"` + } `json:"unassigned_info"` + CanAllocate string `json:"can_allocate"` + CanRemainOnCurrentNode string `json:"can_remain_on_current_node"` + CanRebalanceCluster string `json:"can_rebalance_cluster"` + CanRebalanceToOtherNode string `json:"can_rebalance_to_other_node"` + RebalanceExplanation string `json:"rebalance_explanation"` + AllocateExplanation string `json:"allocate_explanation"` + NodeAllocationDecisions []ClusterAllocationNodeDecisions `json:"node_allocation_decisions"` + CanRebalanceClusterDecisions []ClusterAllocationExplainDeciders `json:"can_rebalance_cluster_decisions"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterAllocationExplainResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterAllocationCurrentNode is a sub type of ClusterAllocationExplainResp containing information of the node the shard is on +type ClusterAllocationCurrentNode struct { + NodeID string `json:"id"` + NodeName string `json:"name"` + TransportAddress string `json:"transport_address"` + NodeAttributes struct { + ShardIndexingPressureEnabled string `json:"shard_indexing_pressure_enabled"` + } `json:"attributes"` + WeightRanking int `json:"weight_ranking"` +} + +// ClusterAllocationNodeDecisions is a sub type of ClusterAllocationExplainResp containing information of a node allocation decission +type ClusterAllocationNodeDecisions struct { + NodeID string `json:"node_id"` + NodeName string `json:"node_name"` + TransportAddress string `json:"transport_address"` + NodeAttributes struct { + ShardIndexingPressureEnabled string `json:"shard_indexing_pressure_enabled"` + } `json:"node_attributes"` + NodeDecision string `json:"node_decision"` + WeightRanking int `json:"weight_ranking"` + Deciders []ClusterAllocationExplainDeciders `json:"deciders"` +} + +// ClusterAllocationExplainDeciders is a sub type of ClusterAllocationExplainResp and +// ClusterAllocationNodeDecisions containing inforamtion about Deciders decissions +type ClusterAllocationExplainDeciders struct { + Decider string `json:"decider"` + Decision string `json:"decision"` + Explanation string `json:"explanation"` +} diff --git a/opensearchapi/api_cluster-decommission-params.go b/opensearchapi/api_cluster-decommission-params.go new file mode 100644 index 000000000..b09080c1a --- /dev/null +++ b/opensearchapi/api_cluster-decommission-params.go @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +// ClusterPutDecommissionParams represents possible parameters for the ClusterPutDecommissionReq +type ClusterPutDecommissionParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterPutDecommissionParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} + +// ClusterGetDecommissionParams represents possible parameters for the ClusterGetDecommissionReq +type ClusterGetDecommissionParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterGetDecommissionParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} + +// ClusterDeleteDecommissionParams represents possible parameters for the ClusterDeleteDecommissionReq +type ClusterDeleteDecommissionParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterDeleteDecommissionParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_cluster-decommission.go b/opensearchapi/api_cluster-decommission.go new file mode 100644 index 000000000..c8ca7d892 --- /dev/null +++ b/opensearchapi/api_cluster-decommission.go @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ClusterPutDecommissionReq represents possible options for the /_cluster/decommission/awareness request +type ClusterPutDecommissionReq struct { + AwarenessAttrName string + AwarenessAttrValue string + + Header http.Header + Params ClusterPutDecommissionParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterPutDecommissionReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(34 + len(r.AwarenessAttrName) + len(r.AwarenessAttrValue)) + path.WriteString("/_cluster/decommission/awareness/") + path.WriteString(r.AwarenessAttrName) + path.WriteString("/") + path.WriteString(r.AwarenessAttrValue) + + return opensearch.BuildRequest( + "PUT", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterPutDecommissionResp represents the returned struct of the /_cluster/decommission/awareness response +type ClusterPutDecommissionResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterPutDecommissionResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterDeleteDecommissionReq represents possible options for the /_cluster/decommission/awareness request +type ClusterDeleteDecommissionReq struct { + Header http.Header + Params ClusterDeleteDecommissionParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterDeleteDecommissionReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + "/_cluster/decommission/awareness", + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterDeleteDecommissionResp represents the returned struct of the /_cluster/decommission/awareness response +type ClusterDeleteDecommissionResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterDeleteDecommissionResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterGetDecommissionReq represents possible options for the /_cluster/decommission/awareness request +type ClusterGetDecommissionReq struct { + AwarenessAttrName string + + Header http.Header + Params ClusterGetDecommissionParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterGetDecommissionReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(41 + len(r.AwarenessAttrName)) + path.WriteString("/_cluster/decommission/awareness/") + path.WriteString(r.AwarenessAttrName) + path.WriteString("/_status") + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterGetDecommissionResp represents the returned struct of the /_cluster/decommission/awareness response +type ClusterGetDecommissionResp struct { + Values map[string]string + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterGetDecommissionResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_cluster-health-params.go b/opensearchapi/api_cluster-health-params.go new file mode 100644 index 000000000..ad2add7f7 --- /dev/null +++ b/opensearchapi/api_cluster-health-params.go @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// ClusterHealthParams represents possible parameters for the ClusterHealthReq +type ClusterHealthParams struct { + ExpandWildcards string + Level string + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + WaitForEvents string + WaitForNoInitializingShards *bool + WaitForNoRelocatingShards *bool + WaitForNodes string + WaitForStatus string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterHealthParams) get() map[string]string { + params := make(map[string]string) + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Level != "" { + params["level"] = r.Level + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.WaitForEvents != "" { + params["wait_for_events"] = r.WaitForEvents + } + + if r.WaitForNoInitializingShards != nil { + params["wait_for_no_initializing_shards"] = strconv.FormatBool(*r.WaitForNoInitializingShards) + } + + if r.WaitForNoRelocatingShards != nil { + params["wait_for_no_relocating_shards"] = strconv.FormatBool(*r.WaitForNoRelocatingShards) + } + + if r.WaitForNodes != "" { + params["wait_for_nodes"] = r.WaitForNodes + } + + if r.WaitForStatus != "" { + params["wait_for_status"] = r.WaitForStatus + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_cluster-health.go b/opensearchapi/api_cluster-health.go new file mode 100644 index 000000000..e5e929f64 --- /dev/null +++ b/opensearchapi/api_cluster-health.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ClusterHealthReq represents possible options for the /_cluster/health request +type ClusterHealthReq struct { + Indices []string + Header http.Header + Params ClusterHealthParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterHealthReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(17 + len(indices)) + path.WriteString("/_cluster/health") + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterHealthResp represents the returned struct of the ClusterHealthReq response +type ClusterHealthResp struct { + ClusterName string `json:"cluster_name"` + Status string `json:"status"` + TimedOut bool `json:"timed_out"` + NumberOfNodes int `json:"number_of_nodes"` + NumberOfDataNodes int `json:"number_of_data_nodes"` + DiscoveredMaster bool `json:"discovered_master"` + DiscoveredClusterManager bool `json:"discovered_cluster_manager"` + ActivePrimaryShards int `json:"active_primary_shards"` + ActiveShards int `json:"active_shards"` + RelocatingShards int `json:"relocating_shards"` + InitializingShards int `json:"initializing_shards"` + UnassignedShards int `json:"unassigned_shards"` + DelayedUnassignedShards int `json:"delayed_unassigned_shards"` + NumberOfPendingTasks int `json:"number_of_pending_tasks"` + NumberOfInFlightFetch int `json:"number_of_in_flight_fetch"` + TaskMaxWaitingInQueueMillis int `json:"task_max_waiting_in_queue_millis"` + ActiveShardsPercentAsNumber float64 `json:"active_shards_percent_as_number"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterHealthResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_cluster-pending_tasks-params.go b/opensearchapi/api_cluster-pending_tasks-params.go new file mode 100644 index 000000000..e3a7b64a2 --- /dev/null +++ b/opensearchapi/api_cluster-pending_tasks-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// ClusterPendingTasksParams represents possible parameters for the ClusterPendingTasksReq +type ClusterPendingTasksParams struct { + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterPendingTasksParams) get() map[string]string { + params := make(map[string]string) + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_cluster-pending_tasks.go b/opensearchapi/api_cluster-pending_tasks.go new file mode 100644 index 000000000..a030239f7 --- /dev/null +++ b/opensearchapi/api_cluster-pending_tasks.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ClusterPendingTasksReq represents possible options for the /_cluster/pending_tasks request +type ClusterPendingTasksReq struct { + Header http.Header + Params ClusterPendingTasksParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterPendingTasksReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cluster/pending_tasks", + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterPendingTasksResp represents the returned struct of the ClusterPendingTasksReq response +type ClusterPendingTasksResp struct { + Tasks []ClusterPendingTasksItem `json:"tasks"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterPendingTasksResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterPendingTasksItem is a sub type if ClusterPendingTasksResp containing information about a task +type ClusterPendingTasksItem struct { + InsertOrder int `json:"insert_order"` + Priority string `json:"priority"` + Source string `json:"source"` + TimeInQueueMillis int `json:"time_in_queue_millis"` + TimeInQueue string `json:"time_in_queue"` + Executing bool `json:"executing"` +} diff --git a/opensearchapi/opensearchapi.request.go b/opensearchapi/api_cluster-remote_info-params.go similarity index 71% rename from opensearchapi/opensearchapi.request.go rename to opensearchapi/api_cluster-remote_info-params.go index 4c83fb3c9..6c99b9d97 100644 --- a/opensearchapi/opensearchapi.request.go +++ b/opensearchapi/api_cluster-remote_info-params.go @@ -26,28 +26,27 @@ package opensearchapi -import ( - "context" - "io" - "net/http" -) +// ClusterRemoteInfoParams represents possible parameters for the ClusterRemoteInfoReq +type ClusterRemoteInfoParams struct { + Pretty bool + Human bool + ErrorTrace bool +} -const ( - headerContentType = "Content-Type" -) +func (r ClusterRemoteInfoParams) get() map[string]string { + params := make(map[string]string) -var ( - headerContentTypeJSON = []string{"application/json"} -) + if r.Pretty { + params["pretty"] = "true" + } -// Request defines the API request. -// -type Request interface { - Do(ctx context.Context, transport Transport) (*Response, error) -} + if r.Human { + params["human"] = "true" + } -// newRequest creates an HTTP request. -// -func newRequest(method, path string, body io.Reader) (*http.Request, error) { - return http.NewRequest(method, path, body) + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params } diff --git a/opensearchapi/api_cluster-remote_info.go b/opensearchapi/api_cluster-remote_info.go new file mode 100644 index 000000000..99643d4fb --- /dev/null +++ b/opensearchapi/api_cluster-remote_info.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ClusterRemoteInfoReq represents possible options for the /_remote/info request +type ClusterRemoteInfoReq struct { + Header http.Header + Params ClusterRemoteInfoParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterRemoteInfoReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_remote/info", + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterRemoteInfoResp represents the returned struct of the ClusterRemoteInfoReq response +type ClusterRemoteInfoResp struct { + Clusters map[string]ClusterRemoteInfoDetails + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterRemoteInfoResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterRemoteInfoDetails is a sub type of ClusterRemoteInfoResp contains information about a remote connection +type ClusterRemoteInfoDetails struct { + Connected bool `json:"connected"` + Mode string `json:"mode"` + Seeds []string `json:"seeds"` + NumNodesConnected int `json:"num_nodes_connected"` + MaxConnectionsPerCluster int `json:"max_connections_per_cluster"` + InitialConnectTimeout string `json:"initial_connect_timeout"` + SkipUnavailable bool `json:"skip_unavailable"` +} diff --git a/opensearchapi/api_cluster-reroute-params.go b/opensearchapi/api_cluster-reroute-params.go new file mode 100644 index 000000000..f2caf5f3a --- /dev/null +++ b/opensearchapi/api_cluster-reroute-params.go @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// ClusterRerouteParams represents possible parameters for the ClusterRerouteReq +type ClusterRerouteParams struct { + DryRun *bool + Explain *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Metric []string + RetryFailed *bool + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterRerouteParams) get() map[string]string { + params := make(map[string]string) + + if r.DryRun != nil { + params["dry_run"] = strconv.FormatBool(*r.DryRun) + } + + if r.Explain != nil { + params["explain"] = strconv.FormatBool(*r.Explain) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if len(r.Metric) > 0 { + params["metric"] = strings.Join(r.Metric, ",") + } + + if r.RetryFailed != nil { + params["retry_failed"] = strconv.FormatBool(*r.RetryFailed) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_cluster-reroute.go b/opensearchapi/api_cluster-reroute.go new file mode 100644 index 000000000..40ba58e6f --- /dev/null +++ b/opensearchapi/api_cluster-reroute.go @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ClusterRerouteReq represents possible options for the /_cluster/reroute request +type ClusterRerouteReq struct { + Body io.Reader + + Header http.Header + Params ClusterRerouteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterRerouteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_cluster/reroute", + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ClusterRerouteResp represents the returned struct of the ClusterRerouteReq response +type ClusterRerouteResp struct { + Acknowledged bool `json:"acknowledged"` + State ClusterRerouteState `json:"state"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterRerouteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterRerouteState is a sub type of ClusterRerouteResp containing information about the cluster and cluster routing +type ClusterRerouteState struct { + ClusterUUID string `json:"cluster_uuid"` + Version int `json:"version"` + StateUUID string `json:"state_uuid"` + MasterNode string `json:"master_node"` + ClusterManagerNode string `json:"cluster_manager_node"` + Blocks json.RawMessage `json:"blocks"` + Nodes map[string]ClusterStateNodes `json:"nodes"` + RoutingTable struct { + Indices map[string]struct { + Shards map[string][]ClusterStateRoutingIndex `json:"shards"` + } `json:"indices"` + } `json:"routing_table"` + RoutingNodes ClusterStateRoutingNodes `json:"routing_nodes"` + RepositoryCleanup struct { + RepositoryCleanup []json.RawMessage `json:"repository_cleanup"` + } `json:"repository_cleanup"` + SnapshotDeletions struct { + SnapshotDeletions []json.RawMessage `json:"snapshot_deletions"` + } `json:"snapshot_deletions"` + Snapshots struct { + Snapshots []json.RawMessage `json:"snapshots"` + } `json:"snapshots"` + Restore struct { + Snapshots []json.RawMessage `json:"snapshots"` + } `json:"restore"` +} diff --git a/opensearchapi/api_cluster-settings-params.go b/opensearchapi/api_cluster-settings-params.go new file mode 100644 index 000000000..7cd53f814 --- /dev/null +++ b/opensearchapi/api_cluster-settings-params.go @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// ClusterGetSettingsParams represents possible parameters for the ClusterGetSettingsReq +type ClusterGetSettingsParams struct { + FlatSettings *bool + IncludeDefaults *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterGetSettingsParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IncludeDefaults != nil { + params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} + +// ClusterPutSettingsParams represents possible parameters for the ClusterGetSettingsReq +type ClusterPutSettingsParams struct { + FlatSettings *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterPutSettingsParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_cluster-settings.go b/opensearchapi/api_cluster-settings.go new file mode 100644 index 000000000..bb5d054a9 --- /dev/null +++ b/opensearchapi/api_cluster-settings.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ClusterGetSettingsReq represents possible options for the /_cluster/settings request +type ClusterGetSettingsReq struct { + Header http.Header + Params ClusterGetSettingsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterGetSettingsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_cluster/settings", + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterGetSettingsResp represents the returned struct of the ClusterGetSettingsReq response +type ClusterGetSettingsResp struct { + Persistent json.RawMessage `json:"persistent"` + Transient json.RawMessage `json:"transient"` + Defaults json.RawMessage `json:"defaults"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterGetSettingsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterPutSettingsReq represents possible options for the /_cluster/settings request +type ClusterPutSettingsReq struct { + Body io.Reader + Header http.Header + Params ClusterPutSettingsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterPutSettingsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + "/_cluster/settings", + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ClusterPutSettingsResp represents the returned struct of the /_cluster/settings response +type ClusterPutSettingsResp struct { + Acknowledged bool `json:"acknowledged"` + Persistent json.RawMessage `json:"persistent"` + Transient json.RawMessage `json:"transient"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterPutSettingsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_cluster-state-params.go b/opensearchapi/api_cluster-state-params.go new file mode 100644 index 000000000..0ec797439 --- /dev/null +++ b/opensearchapi/api_cluster-state-params.go @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// ClusterStateParams represents possible parameters for the ClusterStateReq +type ClusterStateParams struct { + AllowNoIndices *bool + ExpandWildcards string + FlatSettings *bool + IgnoreUnavailable *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + WaitForMetadataVersion *int + WaitForTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterStateParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.WaitForMetadataVersion != nil { + params["wait_for_metadata_version"] = strconv.FormatInt(int64(*r.WaitForMetadataVersion), 10) + } + + if r.WaitForTimeout != 0 { + params["wait_for_timeout"] = formatDuration(r.WaitForTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_cluster-state.go b/opensearchapi/api_cluster-state.go new file mode 100644 index 000000000..34b37426e --- /dev/null +++ b/opensearchapi/api_cluster-state.go @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ClusterStateReq represents possible options for the /_cluster/state request +type ClusterStateReq struct { + Metrics []string + Indices []string + + Header http.Header + Params ClusterStateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterStateReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + metrics := strings.Join(r.Metrics, ",") + + var path strings.Builder + path.Grow(17 + len(indices) + len(metrics)) + path.WriteString("/_cluster/state") + if len(metrics) > 0 { + path.WriteString("/") + path.WriteString(metrics) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterStateResp represents the returned struct of the ClusterStateReq response +type ClusterStateResp struct { + ClusterName string `json:"cluster_name"` + ClusterUUID string `json:"cluster_uuid"` + Version int `json:"version"` + StateUUID string `json:"state_uuid"` + MasterNode string `json:"master_node"` + ClusterManagerNode string `json:"cluster_manager_node"` + Blocks struct { + Indices map[string]map[string]ClusterStateBlocksIndex `json:"indices"` + } `json:"blocks"` + Nodes map[string]ClusterStateNodes `json:"nodes"` + Metadata ClusterStateMetaData `json:"metadata"` + response *opensearch.Response + RoutingTable struct { + Indices map[string]struct { + Shards map[string][]ClusterStateRoutingIndex `json:"shards"` + } `json:"indices"` + } `json:"routing_table"` + RoutingNodes ClusterStateRoutingNodes `json:"routing_nodes"` + Snapshots struct { + Snapshots []json.RawMessage `json:"snapshots"` + } `json:"snapshots"` + SnapshotDeletions struct { + SnapshotDeletions []json.RawMessage `json:"snapshot_deletions"` + } `json:"snapshot_deletions"` + RepositoryCleanup struct { + RepositoryCleanup []json.RawMessage `json:"repository_cleanup"` + } `json:"repository_cleanup"` + Restore struct { + Snapshots []json.RawMessage `json:"snapshots"` + } `json:"restore"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterStateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterStateBlocksIndex is a sub type of ClusterStateResp +type ClusterStateBlocksIndex struct { + Description string `json:"description"` + Retryable bool `json:"retryable"` + Levels []string `json:"levels"` +} + +// ClusterStateNodes is a sub type of ClusterStateResp +type ClusterStateNodes struct { + Name string `json:"name"` + EphemeralID string `json:"ephemeral_id"` + TransportAddress string `json:"transport_address"` + Attributes map[string]string `json:"attributes"` +} + +// ClusterStateMetaData is a sub type if ClusterStateResp containing metadata of the cluster +type ClusterStateMetaData struct { + ClusterUUID string `json:"cluster_uuid"` + ClusterUUIDCommitted bool `json:"cluster_uuid_committed"` + ClusterCoordination struct { + Term int `json:"term"` + LastCommittedConfig []string `json:"last_committed_config"` + LastAcceptedConfig []string `json:"last_accepted_config"` + VotingConfigExclusions []struct { + NodeID string `json:"node_id"` + NodeName string `json:"node_name"` + } `json:"voting_config_exclusions"` + } `json:"cluster_coordination"` + Templates map[string]json.RawMessage `json:"templates"` + Indices map[string]ClusterStateMetaDataIndex `json:"indices"` + IndexGraveyard struct { + Tombstones []struct { + Index struct { + IndexName string `json:"index_name"` + IndexUUID string `json:"index_uuid"` + } `json:"index"` + DeleteDateInMillis int `json:"delete_date_in_millis"` + } `json:"tombstones"` + } `json:"index-graveyard"` + Repositories map[string]struct { + Type string `json:"type"` + Settings map[string]string `json:"settings"` + Generation int `json:"generation"` + PendingGeneration int `json:"pending_generation"` + } `json:"repositories"` + ComponentTemplate struct { + ComponentTemplate map[string]json.RawMessage `json:"component_template"` + } `json:"component_template"` + IndexTemplate struct { + IndexTemplate map[string]json.RawMessage `json:"index_template"` + } `json:"index_template"` + StoredScripts map[string]struct { + Lang string `json:"lang"` + Source string `json:"source"` + } `json:"stored_scripts"` + Ingest struct { + Pipeline []struct { + ID string `json:"id"` + Config struct { + Description string `json:"description"` + Processors json.RawMessage `json:"processors"` + } `json:"config"` + } `json:"pipeline"` + } `json:"ingest"` + DataStream struct { + DataStream map[string]ClusterStateMetaDataStream `json:"data_stream"` + } `json:"data_stream"` +} + +// ClusterStateMetaDataIndex is a sub type of ClusterStateMetaData containing information about an index +type ClusterStateMetaDataIndex struct { + Version int `json:"version"` + MappingVersion int `json:"mapping_version"` + SettingsVersion int `json:"settings_version"` + AliasesVersion int `json:"aliases_version"` + RoutingNumShards int `json:"routing_num_shards"` + State string `json:"state"` + Settings json.RawMessage `json:"settings"` + Mappings json.RawMessage `json:"mappings"` + Aliases []string `json:"aliases"` + PrimaryTerms map[string]int `json:"primary_terms"` + InSyncAllocations map[string][]string `json:"in_sync_allocations"` + RolloverInfo map[string]struct { + MetConditions map[string]string `json:"met_conditions"` + Time int `json:"time"` + } `json:"rollover_info"` + System bool `json:"system"` +} + +// ClusterStateMetaDataStream is a sub type of ClusterStateMetaData containing information about a data stream +type ClusterStateMetaDataStream struct { + Name string `json:"name"` + TimestampField struct { + Name string `json:"name"` + } `json:"timestamp_field"` + Indices []struct { + IndexName string `json:"index_name"` + IndexUUID string `json:"index_uuid"` + } `json:"indices"` + Generation int `json:"generation"` +} + +// ClusterStateRoutingIndex is a sub type of ClusterStateResp and ClusterStateRoutingNodes containing information about shard routing +type ClusterStateRoutingIndex struct { + State string `json:"state"` + Primary bool `json:"primary"` + Node *string `json:"node"` + RelocatingNode *string `json:"relocating_node"` + Shard int `json:"shard"` + Index string `json:"index"` + ExpectedShardSizeInBytes int `json:"expected_shard_size_in_bytes"` + AllocationID *struct { + ID string `json:"id"` + } `json:"allocation_id,omitempty"` + RecoverySource *struct { + Type string `json:"type"` + } `json:"recovery_source,omitempty"` + UnassignedInfo *struct { + Reason string `json:"reason"` + At string `json:"at"` + Delayed bool `json:"delayed"` + AllocationStatus string `json:"allocation_status"` + Details string `json:"details"` + } `json:"unassigned_info,omitempty"` +} + +// ClusterStateRoutingNodes is a sub type of ClusterStateResp containing information about shard assigned to nodes +type ClusterStateRoutingNodes struct { + Unassigned []ClusterStateRoutingIndex `json:"unassigned"` + Nodes map[string][]ClusterStateRoutingIndex `json:"nodes"` +} diff --git a/opensearchapi/api_cluster-stats-params.go b/opensearchapi/api_cluster-stats-params.go new file mode 100644 index 000000000..630278753 --- /dev/null +++ b/opensearchapi/api_cluster-stats-params.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// ClusterStatsParams represents possible parameters for the ClusterStatsReq +type ClusterStatsParams struct { + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterStatsParams) get() map[string]string { + params := make(map[string]string) + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_cluster-stats.go b/opensearchapi/api_cluster-stats.go new file mode 100644 index 000000000..6500b786c --- /dev/null +++ b/opensearchapi/api_cluster-stats.go @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ClusterStatsReq represents possible options for the /_cluster/stats request +type ClusterStatsReq struct { + NodeFilters []string + + Header http.Header + Params ClusterStatsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterStatsReq) GetRequest() (*http.Request, error) { + filters := strings.Join(r.NodeFilters, ",") + + var path strings.Builder + path.Grow(22 + len(filters)) + path.WriteString("/_cluster/stats") + if len(filters) > 0 { + path.WriteString("/nodes/") + path.WriteString(filters) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterStatsResp represents the returned struct of the ClusterStatsReq response +type ClusterStatsResp struct { + NodesInfo struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + ClusterUUID string `json:"cluster_uuid"` + Timestamp int64 `json:"timestamp"` + Status string `json:"status"` + Indices ClusterStatsIndices `json:"indices"` + Nodes ClusterStatsNodes `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ClusterStatsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ClusterStatsIndices is a sub type of ClusterStatsResp containing cluster information about indices +type ClusterStatsIndices struct { + Count int `json:"count"` + Shards struct { + Total int `json:"total"` + Primaries int `json:"primaries"` + Replication float64 `json:"replication"` + Index struct { + Shards struct { + Min float64 `json:"min"` + Max float64 `json:"max"` + Avg float64 `json:"avg"` + } `json:"shards"` + Primaries struct { + Min float64 `json:"min"` + Max float64 `json:"max"` + Avg float64 `json:"avg"` + } `json:"primaries"` + Replication struct { + Min float64 `json:"min"` + Max float64 `json:"max"` + Avg float64 `json:"avg"` + } `json:"replication"` + } `json:"index"` + } `json:"shards"` + Docs struct { + Count int64 `json:"count"` + Deleted int `json:"deleted"` + } `json:"docs"` + Store struct { + SizeInBytes int64 `json:"size_in_bytes"` + ReservedInBytes int `json:"reserved_in_bytes"` + } `json:"store"` + Fielddata struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + Evictions int `json:"evictions"` + } `json:"fielddata"` + QueryCache struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + TotalCount int `json:"total_count"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` + CacheSize int `json:"cache_size"` + CacheCount int `json:"cache_count"` + Evictions int `json:"evictions"` + } `json:"query_cache"` + Completion struct { + SizeInBytes int `json:"size_in_bytes"` + } `json:"completion"` + Segments struct { + Count int `json:"count"` + MemoryInBytes int `json:"memory_in_bytes"` + TermsMemoryInBytes int `json:"terms_memory_in_bytes"` + StoredFieldsMemoryInBytes int `json:"stored_fields_memory_in_bytes"` + TermVectorsMemoryInBytes int `json:"term_vectors_memory_in_bytes"` + NormsMemoryInBytes int `json:"norms_memory_in_bytes"` + PointsMemoryInBytes int `json:"points_memory_in_bytes"` + DocValuesMemoryInBytes int `json:"doc_values_memory_in_bytes"` + IndexWriterMemoryInBytes int `json:"index_writer_memory_in_bytes"` + VersionMapMemoryInBytes int `json:"version_map_memory_in_bytes"` + FixedBitSetMemoryInBytes int64 `json:"fixed_bit_set_memory_in_bytes"` + MaxUnsafeAutoIDTimestamp int64 `json:"max_unsafe_auto_id_timestamp"` + RemoteStore struct { + Upload struct { + TotalUploadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_upload_size"` + RefreshSizeLag struct { + TotalBytes int `json:"total_bytes"` + MaxBytes int `json:"max_bytes"` + } `json:"refresh_size_lag"` + MaxRefreshTimeLagInMillis int `json:"max_refresh_time_lag_in_millis"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + } `json:"upload"` + Download struct { + TotalDownloadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_download_size"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + } `json:"download"` + } `json:"remote_store"` + SegmentReplication struct { + // Type is json.RawMessage due to difference in opensearch versions from string to int + MaxBytesBehind json.RawMessage `json:"max_bytes_behind"` + TotalBytesBehind json.RawMessage `json:"total_bytes_behind"` + MaxReplicationLag json.RawMessage `json:"max_replication_lag"` + } `json:"segment_replication"` + FileSizes json.RawMessage `json:"file_sizes"` + } `json:"segments"` + Mappings struct { + FieldTypes []struct { + Name string `json:"name"` + Count int `json:"count"` + IndexCount int `json:"index_count"` + } `json:"field_types"` + } `json:"mappings"` + Analysis struct { + CharFilterTypes []json.RawMessage `json:"char_filter_types"` + TokenizerTypes []json.RawMessage `json:"tokenizer_types"` + FilterTypes []json.RawMessage `json:"filter_types"` + AnalyzerTypes []json.RawMessage `json:"analyzer_types"` + BuiltInCharFilters []json.RawMessage `json:"built_in_char_filters"` + BuiltInTokenizers []json.RawMessage `json:"built_in_tokenizers"` + BuiltInFilters []json.RawMessage `json:"built_in_filters"` + BuiltInAnalyzers []json.RawMessage `json:"built_in_analyzers"` + } `json:"analysis"` + RepositoryCleanup struct { + RepositoryCleanup []json.RawMessage `json:"repository_cleanup"` + } `json:"repository_cleanup"` +} + +// ClusterStatsNodes is a sub type of ClusterStatsResp containing information about node stats +type ClusterStatsNodes struct { + Count struct { + Total int `json:"total"` + ClusterManager int `json:"cluster_manager"` + CoordinatingOnly int `json:"coordinating_only"` + Data int `json:"data"` + Ingest int `json:"ingest"` + Master int `json:"master"` + RemoteClusterClient int `json:"remote_cluster_client"` + Search int `json:"search"` + } `json:"count"` + Versions []string `json:"versions"` + Os struct { + AvailableProcessors int `json:"available_processors"` + AllocatedProcessors int `json:"allocated_processors"` + Names []struct { + Name string `json:"name"` + Count int `json:"count"` + } `json:"names"` + PrettyNames []struct { + PrettyName string `json:"pretty_name"` + Count int `json:"count"` + } `json:"pretty_names"` + Mem struct { + TotalInBytes int64 `json:"total_in_bytes"` + FreeInBytes int64 `json:"free_in_bytes"` + UsedInBytes int64 `json:"used_in_bytes"` + FreePercent int `json:"free_percent"` + UsedPercent int `json:"used_percent"` + } `json:"mem"` + } `json:"os"` + Process struct { + CPU struct { + Percent int `json:"percent"` + } `json:"cpu"` + OpenFileDescriptors struct { + Min int `json:"min"` + Max int `json:"max"` + Avg int `json:"avg"` + } `json:"open_file_descriptors"` + } `json:"process"` + Jvm struct { + MaxUptimeInMillis int64 `json:"max_uptime_in_millis"` + Versions []struct { + Version string `json:"version"` + VMName string `json:"vm_name"` + VMVersion string `json:"vm_version"` + VMVendor string `json:"vm_vendor"` + BundledJdk bool `json:"bundled_jdk"` + UsingBundledJdk bool `json:"using_bundled_jdk"` + Count int `json:"count"` + } `json:"versions"` + Mem struct { + HeapUsedInBytes int64 `json:"heap_used_in_bytes"` + HeapMaxInBytes int64 `json:"heap_max_in_bytes"` + } `json:"mem"` + Threads int `json:"threads"` + } `json:"jvm"` + Fs struct { + TotalInBytes int64 `json:"total_in_bytes"` + FreeInBytes int64 `json:"free_in_bytes"` + AvailableInBytes int64 `json:"available_in_bytes"` + CacheReservedInBytes int `json:"cache_reserved_in_bytes"` + } `json:"fs"` + Plugins []struct { + Name string `json:"name"` + Version string `json:"version"` + OpensearchVersion string `json:"opensearch_version"` + JavaVersion string `json:"java_version"` + Description string `json:"description"` + Classname string `json:"classname"` + CustomFoldername string `json:"custom_foldername"` + ExtendedPlugins []string `json:"extended_plugins"` + HasNativeController bool `json:"has_native_controller"` + } `json:"plugins"` + NetworkTypes struct { + TransportTypes map[string]int `json:"transport_types"` + HTTPTypes map[string]int `json:"http_types"` + } `json:"network_types"` + DiscoveryTypes map[string]int `json:"discovery_types"` + PackagingTypes []struct { + Type string `json:"type"` + Count int `json:"count"` + } `json:"packaging_types"` + Ingest struct { + NumberOfPipelines int `json:"number_of_pipelines"` + ProcessorStats json.RawMessage `json:"processor_stats"` + } `json:"ingest"` +} diff --git a/opensearchapi/api_cluster-voting_config_exclusions-params.go b/opensearchapi/api_cluster-voting_config_exclusions-params.go new file mode 100644 index 000000000..ac178337a --- /dev/null +++ b/opensearchapi/api_cluster-voting_config_exclusions-params.go @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// ClusterPostVotingConfigExclusionsParams represents possible parameters for the ClusterVotingConfigExclusionsReq +type ClusterPostVotingConfigExclusionsParams struct { + NodeIds string + NodeNames string + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterPostVotingConfigExclusionsParams) get() map[string]string { + params := make(map[string]string) + + if r.NodeIds != "" { + params["node_ids"] = r.NodeIds + } + + if r.NodeNames != "" { + params["node_names"] = r.NodeNames + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} + +// ClusterDeleteVotingConfigExclusionsParams represents possible parameters for the ClusterVotingConfigExclusionsReq +type ClusterDeleteVotingConfigExclusionsParams struct { + WaitForRemoval *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ClusterDeleteVotingConfigExclusionsParams) get() map[string]string { + params := make(map[string]string) + + if r.WaitForRemoval != nil { + params["wait_for_removal"] = strconv.FormatBool(*r.WaitForRemoval) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_cluster-voting_config_exclusions.go b/opensearchapi/api_cluster-voting_config_exclusions.go new file mode 100644 index 000000000..46736459c --- /dev/null +++ b/opensearchapi/api_cluster-voting_config_exclusions.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ClusterPostVotingConfigExclusionsReq represents possible options for the /_cluster/voting_config_exclusions request +type ClusterPostVotingConfigExclusionsReq struct { + Header http.Header + Params ClusterPostVotingConfigExclusionsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterPostVotingConfigExclusionsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_cluster/voting_config_exclusions", + nil, + r.Params.get(), + r.Header, + ) +} + +// ClusterDeleteVotingConfigExclusionsReq represents possible options for the /_cluster/voting_config_exclusions request +type ClusterDeleteVotingConfigExclusionsReq struct { + Header http.Header + Params ClusterDeleteVotingConfigExclusionsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ClusterDeleteVotingConfigExclusionsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + "/_cluster/voting_config_exclusions", + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/opensearchapi/api_cluster.go b/opensearchapi/api_cluster.go new file mode 100644 index 000000000..40ad57a5f --- /dev/null +++ b/opensearchapi/api_cluster.go @@ -0,0 +1,241 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v2" +) + +type clusterClient struct { + apiClient *Client +} + +// AllocationExplain executes a /_cluster/allocation/explain request with the optional ClusterAllocationExplainReq +func (c clusterClient) AllocationExplain(ctx context.Context, req *ClusterAllocationExplainReq) (*ClusterAllocationExplainResp, error) { + if req == nil { + req = &ClusterAllocationExplainReq{} + } + + var ( + data ClusterAllocationExplainResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Health executes a /_cluster/health request with the optional ClusterHealthReq +func (c clusterClient) Health(ctx context.Context, req *ClusterHealthReq) (*ClusterHealthResp, error) { + if req == nil { + req = &ClusterHealthReq{} + } + + var ( + data ClusterHealthResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// PendingTasks executes a /_cluster/pending_tasks request with the optional ClusterPendingTasksReq +func (c clusterClient) PendingTasks(ctx context.Context, req *ClusterPendingTasksReq) (*ClusterPendingTasksResp, error) { + if req == nil { + req = &ClusterPendingTasksReq{} + } + + var ( + data ClusterPendingTasksResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// GetSettings executes a /_cluster/settings request with the optional ClusterGetSettingsReq +func (c clusterClient) GetSettings(ctx context.Context, req *ClusterGetSettingsReq) (*ClusterGetSettingsResp, error) { + if req == nil { + req = &ClusterGetSettingsReq{} + } + + var ( + data ClusterGetSettingsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// PutSettings executes a /_cluster/settings request with the required ClusterPutSettingsReq +func (c clusterClient) PutSettings(ctx context.Context, req ClusterPutSettingsReq) (*ClusterPutSettingsResp, error) { + var ( + data ClusterPutSettingsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// State executes a /_cluster/state request with the optional ClusterStateReq +func (c clusterClient) State(ctx context.Context, req *ClusterStateReq) (*ClusterStateResp, error) { + if req == nil { + req = &ClusterStateReq{} + } + + var ( + data ClusterStateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Stats executes a /_cluster/stats request with the optional ClusterStatsReq +func (c clusterClient) Stats(ctx context.Context, req *ClusterStatsReq) (*ClusterStatsResp, error) { + if req == nil { + req = &ClusterStatsReq{} + } + + var ( + data ClusterStatsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Reroute executes a /_cluster/reroute request with the required ClusterRerouteReq +func (c clusterClient) Reroute(ctx context.Context, req ClusterRerouteReq) (*ClusterRerouteResp, error) { + var ( + data ClusterRerouteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// PostVotingConfigExclusions executes a /_cluster/voting_config_exclusions request with the optional ClusterPostVotingConfigExclusionsReq +func (c clusterClient) PostVotingConfigExclusions( + ctx context.Context, + req ClusterPostVotingConfigExclusionsReq, +) (*opensearch.Response, error) { + var ( + resp *opensearch.Response + err error + ) + if resp, err = c.apiClient.do(ctx, req, nil); err != nil { + return resp, err + } + + return resp, nil +} + +// DeleteVotingConfigExclusions executes a /_cluster/voting_config_exclusions request +// with the optional ClusterDeleteVotingConfigExclusionsReq +func (c clusterClient) DeleteVotingConfigExclusions( + ctx context.Context, + req ClusterDeleteVotingConfigExclusionsReq, +) (*opensearch.Response, error) { + var ( + resp *opensearch.Response + err error + ) + if resp, err = c.apiClient.do(ctx, req, nil); err != nil { + return resp, err + } + + return resp, nil +} + +// PutDecommission executes a /_cluster/decommission/awareness request with the optional ClusterPutDecommissionReq +func (c clusterClient) PutDecommission(ctx context.Context, req ClusterPutDecommissionReq) (*ClusterPutDecommissionResp, error) { + var ( + data ClusterPutDecommissionResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// DeleteDecommission executes a /_cluster/decommission/awareness request with the optional ClusterDeleteDecommissionReq +func (c clusterClient) DeleteDecommission( + ctx context.Context, + req *ClusterDeleteDecommissionReq, +) (*ClusterDeleteDecommissionResp, error) { + if req == nil { + req = &ClusterDeleteDecommissionReq{} + } + + var ( + data ClusterDeleteDecommissionResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// GetDecommission executes a /_cluster/decommission/awareness request with the optional ClusterGetDecommissionReq +func (c clusterClient) GetDecommission(ctx context.Context, req ClusterGetDecommissionReq) (*ClusterGetDecommissionResp, error) { + var ( + data ClusterGetDecommissionResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Values); err != nil { + return &data, err + } + + return &data, nil +} + +// RemoteInfo executes a /_remote/info request with the optional ClusterRemoteInfoReq +func (c clusterClient) RemoteInfo(ctx context.Context, req *ClusterRemoteInfoReq) (*ClusterRemoteInfoResp, error) { + if req == nil { + req = &ClusterRemoteInfoReq{} + } + + var ( + data ClusterRemoteInfoResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Clusters); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_cluster_test.go b/opensearchapi/api_cluster_test.go new file mode 100644 index 000000000..88ba0f6e9 --- /dev/null +++ b/opensearchapi/api_cluster_test.go @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestClusterClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + index := "test-cluster-indices" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{index}}) + }) + + _, err = client.Indices.Create(nil, opensearchapi.IndicesCreateReq{Index: index}) + require.Nil(t, err) + + type clusterTest struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := map[string][]clusterTest{ + "AllocationExplain": []clusterTest{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cluster.AllocationExplain(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.AllocationExplain(nil, &opensearchapi.ClusterAllocationExplainReq{Body: &opensearchapi.ClusterAllocationExplainBody{Index: index, Shard: 0, Primary: true}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cluster.AllocationExplain(nil, nil) }, + }, + }, + "Health": []clusterTest{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cluster.Health(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.Health(nil, &opensearchapi.ClusterHealthReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cluster.Health(nil, nil) }, + }, + }, + "PendingTasks": []clusterTest{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cluster.PendingTasks(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.PendingTasks(nil, &opensearchapi.ClusterPendingTasksReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cluster.PendingTasks(nil, nil) }, + }, + }, + "GetSettings": []clusterTest{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cluster.GetSettings(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.GetSettings(nil, &opensearchapi.ClusterGetSettingsReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cluster.GetSettings(nil, nil) }, + }, + }, + "PutSettings": []clusterTest{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.PutSettings(nil, opensearchapi.ClusterPutSettingsReq{Body: strings.NewReader(`{"transient":{"indices":{"recovery":{"max_bytes_per_sec":null}}}}`)}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Cluster.PutSettings(nil, opensearchapi.ClusterPutSettingsReq{}) + }, + }, + }, + "Reroute": []clusterTest{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.Reroute(nil, opensearchapi.ClusterRerouteReq{Body: strings.NewReader(`{}`)}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Cluster.Reroute(nil, opensearchapi.ClusterRerouteReq{Body: strings.NewReader(`{}`)}) + }, + }, + }, + "State": []clusterTest{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cluster.State(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.State(nil, &opensearchapi.ClusterStateReq{Metrics: []string{"_all"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cluster.State(nil, nil) }, + }, + }, + "Stats": []clusterTest{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cluster.Stats(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.Stats(nil, &opensearchapi.ClusterStatsReq{NodeFilters: []string{"data:true"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cluster.Stats(nil, nil) }, + }, + }, + "PutDecommission": []clusterTest{ + /* Needs node awarness attr to work + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.PutDecommission(nil, opensearchapi.ClusterPutDecommissionReq{AwarenessAttrName: "test", AwarenessAttrValue: "test"}) + }, + }, + */ + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Cluster.PutDecommission(nil, opensearchapi.ClusterPutDecommissionReq{AwarenessAttrName: "test", AwarenessAttrValue: "test"}) + }, + }, + }, + "GetDecommission": []clusterTest{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.GetDecommission(nil, opensearchapi.ClusterGetDecommissionReq{AwarenessAttrName: "test"}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Cluster.GetDecommission(nil, opensearchapi.ClusterGetDecommissionReq{AwarenessAttrName: "test"}) + }, + }, + }, + "DeleteDecommission": []clusterTest{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cluster.DeleteDecommission(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.DeleteDecommission(nil, &opensearchapi.ClusterDeleteDecommissionReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cluster.DeleteDecommission(nil, nil) }, + }, + }, + "RemoteInfo": []clusterTest{ + { + Name: "with nil request", + Results: func() (osapitest.Response, error) { return client.Cluster.RemoteInfo(nil, nil) }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Cluster.RemoteInfo(nil, &opensearchapi.ClusterRemoteInfoReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { return failingClient.Cluster.RemoteInfo(nil, nil) }, + }, + }, + } + for catType, value := range testCases { + t.Run(catType, func(t *testing.T) { + if strings.Contains(catType, "Decommission") { + osapitest.SkipIfBelowVersion(t, client, 2, 3, catType) + } + for _, testCase := range value { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + assert.Nil(t, err) + assert.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + }) + } + }) + } +} diff --git a/opensearchapi/api_component_template-create-params.go b/opensearchapi/api_component_template-create-params.go new file mode 100644 index 000000000..8fa51ed9a --- /dev/null +++ b/opensearchapi/api_component_template-create-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// ComponentTemplateCreateParams represents possible parameters for the ComponentTemplateCreateReq +type ComponentTemplateCreateParams struct { + Create *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ComponentTemplateCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.Create != nil { + params["create"] = strconv.FormatBool(*r.Create) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_component_template-create.go b/opensearchapi/api_component_template-create.go new file mode 100644 index 000000000..9a9c56762 --- /dev/null +++ b/opensearchapi/api_component_template-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ComponentTemplateCreateReq represents possible options for the _component_template create request +type ComponentTemplateCreateReq struct { + ComponentTemplate string + + Body io.Reader + + Header http.Header + Params ComponentTemplateCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ComponentTemplateCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_component_template/%s", r.ComponentTemplate), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ComponentTemplateCreateResp represents the returned struct of the index create response +type ComponentTemplateCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ComponentTemplateCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_component_template-delete-params.go b/opensearchapi/api_component_template-delete-params.go new file mode 100644 index 000000000..e150f64b9 --- /dev/null +++ b/opensearchapi/api_component_template-delete-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// ComponentTemplateDeleteParams represents possible parameters for the ComponentTemplateDeleteReq +type ComponentTemplateDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ComponentTemplateDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_component_template-delete.go b/opensearchapi/api_component_template-delete.go new file mode 100644 index 000000000..750139009 --- /dev/null +++ b/opensearchapi/api_component_template-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ComponentTemplateDeleteReq represents possible options for the _component_template delete request +type ComponentTemplateDeleteReq struct { + ComponentTemplate string + + Header http.Header + Params ComponentTemplateDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ComponentTemplateDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_component_template/%s", r.ComponentTemplate), + nil, + r.Params.get(), + r.Header, + ) +} + +// ComponentTemplateDeleteResp represents the returned struct of the _component_template delete response +type ComponentTemplateDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ComponentTemplateDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_component_template-exists-params.go b/opensearchapi/api_component_template-exists-params.go new file mode 100644 index 000000000..effeed6f3 --- /dev/null +++ b/opensearchapi/api_component_template-exists-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// ComponentTemplateExistsParams represents possible parameters for the ComponentTemplateExistsReq +type ComponentTemplateExistsParams struct { + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ComponentTemplateExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_component_template-exists.go b/opensearchapi/api_component_template-exists.go new file mode 100644 index 000000000..a13abc380 --- /dev/null +++ b/opensearchapi/api_component_template-exists.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ComponentTemplateExistsReq represents possible options for the _component_template exists request +type ComponentTemplateExistsReq struct { + ComponentTemplate string + + Header http.Header + Params ComponentTemplateExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ComponentTemplateExistsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("/_component_template/%s", r.ComponentTemplate), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/opensearchapi/api_component_template-get-params.go b/opensearchapi/api_component_template-get-params.go new file mode 100644 index 000000000..cb73cf36c --- /dev/null +++ b/opensearchapi/api_component_template-get-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// ComponentTemplateGetParams represents possible parameters for the ComponentTemplateGetReq +type ComponentTemplateGetParams struct { + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ComponentTemplateGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_component_template-get.go b/opensearchapi/api_component_template-get.go new file mode 100644 index 000000000..6587a048a --- /dev/null +++ b/opensearchapi/api_component_template-get.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ComponentTemplateGetReq represents possible options for the _component_template get request +type ComponentTemplateGetReq struct { + ComponentTemplate string + + Header http.Header + Params ComponentTemplateGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ComponentTemplateGetReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("/_component_template/") + len(r.ComponentTemplate)) + path.WriteString("/_component_template") + if len(r.ComponentTemplate) > 0 { + path.WriteString("/") + path.WriteString(r.ComponentTemplate) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// ComponentTemplateGetResp represents the returned struct of the index create response +type ComponentTemplateGetResp struct { + ComponentTemplates []ComponentTemplateGetDetails `json:"component_templates"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ComponentTemplateGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// ComponentTemplateGetDetails is a sub type of ComponentTemplateGetResp containing information about component template +type ComponentTemplateGetDetails struct { + Name string `json:"name"` + ComponentTemplate struct { + Template struct { + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` + } `json:"template"` + } `json:"component_template"` +} diff --git a/opensearchapi/api_component_template.go b/opensearchapi/api_component_template.go new file mode 100644 index 000000000..a0a6810b3 --- /dev/null +++ b/opensearchapi/api_component_template.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v2" +) + +type componentTemplateClient struct { + apiClient *Client +} + +// Create executes a creade componentTemplate request with the required ComponentTemplateCreateReq +func (c componentTemplateClient) Create(ctx context.Context, req ComponentTemplateCreateReq) (*ComponentTemplateCreateResp, error) { + var ( + data ComponentTemplateCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete componentTemplate request with the required ComponentTemplateDeleteReq +func (c componentTemplateClient) Delete(ctx context.Context, req ComponentTemplateDeleteReq) (*ComponentTemplateDeleteResp, error) { + var ( + data ComponentTemplateDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get componentTemplate request with the optional ComponentTemplateGetReq +func (c componentTemplateClient) Get(ctx context.Context, req *ComponentTemplateGetReq) (*ComponentTemplateGetResp, error) { + if req == nil { + req = &ComponentTemplateGetReq{} + } + + var ( + data ComponentTemplateGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes a exists componentTemplate request with the required ComponentTemplatExistsReq +func (c componentTemplateClient) Exists(ctx context.Context, req ComponentTemplateExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} diff --git a/opensearchapi/api_component_template_test.go b/opensearchapi/api_component_template_test.go new file mode 100644 index 000000000..1bed017c1 --- /dev/null +++ b/opensearchapi/api_component_template_test.go @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestComponentTemplateClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + componentTemplate := "component-template-test" + + type componentTemplateTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []componentTemplateTests + }{ + { + Name: "Create", + Tests: []componentTemplateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.ComponentTemplate.Create( + nil, + opensearchapi.ComponentTemplateCreateReq{ + ComponentTemplate: componentTemplate, + Body: strings.NewReader(`{"template":{"settings":{"index":{"number_of_shards":"2","number_of_replicas":"0"}}}}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.ComponentTemplate.Create(nil, opensearchapi.ComponentTemplateCreateReq{ComponentTemplate: componentTemplate}) + }, + }, + }, + }, + { + Name: "Get", + Tests: []componentTemplateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.ComponentTemplate.Get(nil, &opensearchapi.ComponentTemplateGetReq{ComponentTemplate: componentTemplate}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.ComponentTemplate.Get(nil, nil) + }, + }, + }, + }, + { + Name: "Exists", + Tests: []componentTemplateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = client.ComponentTemplate.Exists(nil, opensearchapi.ComponentTemplateExistsReq{ComponentTemplate: componentTemplate}) + return resp, err + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = failingClient.ComponentTemplate.Exists(nil, opensearchapi.ComponentTemplateExistsReq{ComponentTemplate: componentTemplate}) + return resp, err + }, + }, + }, + }, + { + Name: "Delete", + Tests: []componentTemplateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.ComponentTemplate.Delete(nil, opensearchapi.ComponentTemplateDeleteReq{ComponentTemplate: componentTemplate}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.ComponentTemplate.Delete(nil, opensearchapi.ComponentTemplateDeleteReq{ComponentTemplate: componentTemplate}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + if value.Name != "Exists" { + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + } + }) + } + }) + } +} diff --git a/opensearchapi/api_dangling-delete-params.go b/opensearchapi/api_dangling-delete-params.go new file mode 100644 index 000000000..4d785bc66 --- /dev/null +++ b/opensearchapi/api_dangling-delete-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// DanglingDeleteParams represents possible parameters for the DanglingDeleteReq +type DanglingDeleteParams struct { + AcceptDataLoss *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DanglingDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.AcceptDataLoss != nil { + params["accept_data_loss"] = strconv.FormatBool(*r.AcceptDataLoss) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_dangling-delete.go b/opensearchapi/api_dangling-delete.go new file mode 100644 index 000000000..d92eef5bb --- /dev/null +++ b/opensearchapi/api_dangling-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DanglingDeleteReq represents possible options for the delete dangling request +type DanglingDeleteReq struct { + IndexUUID string + + Header http.Header + Params DanglingDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DanglingDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_dangling/%s", r.IndexUUID), + nil, + r.Params.get(), + r.Header, + ) +} + +// DanglingDeleteResp represents the returned struct of the delete dangling response +type DanglingDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DanglingDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/internal/build/cmd/commands.go b/opensearchapi/api_dangling-get-params.go similarity index 68% rename from internal/build/cmd/commands.go rename to opensearchapi/api_dangling-get-params.go index a1ef44149..b76f38292 100644 --- a/internal/build/cmd/commands.go +++ b/opensearchapi/api_dangling-get-params.go @@ -24,32 +24,29 @@ // specific language governing permissions and limitations // under the License. -package cmd +package opensearchapi -import ( - "os" +// DanglingGetParams represents possible parameters for the DanglingGetReq +type DanglingGetParams struct { + Pretty bool + Human bool + ErrorTrace bool +} - "github.com/spf13/cobra" +func (r DanglingGetParams) get() map[string]string { + params := make(map[string]string) - "github.com/opensearch-project/opensearch-go/v2/internal/build/utils" -) + if r.Pretty { + params["pretty"] = "true" + } -var rootCmd = &cobra.Command{ - Use: "build", - Short: "Build tools for Elasticsearch client, helpers for CI, etc...", -} + if r.Human { + params["human"] = "true" + } -// Execute launches the CLI application. -// -func Execute() { - if err := rootCmd.Execute(); err != nil { - utils.PrintErr(err) - os.Exit(1) + if r.ErrorTrace { + params["error_trace"] = "true" } -} -// RegisterCmd adds a command to rootCmd. -// -func RegisterCmd(cmd *cobra.Command) { - rootCmd.AddCommand(cmd) + return params } diff --git a/opensearchapi/api_dangling-get.go b/opensearchapi/api_dangling-get.go new file mode 100644 index 000000000..cc307b75f --- /dev/null +++ b/opensearchapi/api_dangling-get.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DanglingGetReq represents possible options for the dangling get request +type DanglingGetReq struct { + Header http.Header + Params DanglingGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DanglingGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_dangling", + nil, + r.Params.get(), + r.Header, + ) +} + +// DanglingGetResp represents the returned struct of the dangling get response +type DanglingGetResp struct { + Nodes struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []struct { + Type string `json:"type"` + Reason string `json:"reason"` + NodeID string `json:"node_id"` + CausedBy struct { + Type string `json:"type"` + Reason string `json:"reason"` + } `json:"caused_by"` + } `json:"failures"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + DanglingIndices []struct { + IndexName string `json:"index_name"` + IndexUUID string `json:"index_uuid"` + CreationDateMillis int64 `json:"creation_date_millis"` + NodeIds []string `json:"node_ids"` + } `json:"dangling_indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DanglingGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_dangling-import-params.go b/opensearchapi/api_dangling-import-params.go new file mode 100644 index 000000000..fb4858b71 --- /dev/null +++ b/opensearchapi/api_dangling-import-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// DanglingImportParams represents possible parameters for the DanglingImportReq +type DanglingImportParams struct { + AcceptDataLoss *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DanglingImportParams) get() map[string]string { + params := make(map[string]string) + + if r.AcceptDataLoss != nil { + params["accept_data_loss"] = strconv.FormatBool(*r.AcceptDataLoss) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_dangling-import.go b/opensearchapi/api_dangling-import.go new file mode 100644 index 000000000..e0f915340 --- /dev/null +++ b/opensearchapi/api_dangling-import.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DanglingImportReq represents possible options for the dangling import request +type DanglingImportReq struct { + IndexUUID string + + Header http.Header + Params DanglingImportParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DanglingImportReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_dangling/%s", r.IndexUUID), + nil, + r.Params.get(), + r.Header, + ) +} + +// DanglingImportResp represents the returned struct of thedangling import response +type DanglingImportResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DanglingImportResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_dangling.go b/opensearchapi/api_dangling.go new file mode 100644 index 000000000..60922fde2 --- /dev/null +++ b/opensearchapi/api_dangling.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type danglingClient struct { + apiClient *Client +} + +// Delete executes a delete dangling request with the required DanglingDeleteReq +func (c danglingClient) Delete(ctx context.Context, req DanglingDeleteReq) (*DanglingDeleteResp, error) { + var ( + data DanglingDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Import executes an import dangling request with the required DanglingImportReq +func (c danglingClient) Import(ctx context.Context, req DanglingImportReq) (*DanglingImportResp, error) { + var ( + data DanglingImportResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a /_dangling request with the optional DanglingGetReq +func (c danglingClient) Get(ctx context.Context, req *DanglingGetReq) (*DanglingGetResp, error) { + if req == nil { + req = &DanglingGetReq{} + } + + var ( + data DanglingGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_dangling_test.go b/opensearchapi/api_dangling_test.go new file mode 100644 index 000000000..c0b284cee --- /dev/null +++ b/opensearchapi/api_dangling_test.go @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestDanglingClient(t *testing.T) { + // Testing dangling indices would require manipulating data inside the opensearch server container + // instead we create a http servers that returns the expected status code and body + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + testURL := func(u *url.URL) (int, string) { + if u.Path != "/_dangling/indexUUID" { + return http.StatusNotImplemented, fmt.Sprintf(`{"status": 501, "error": "Expected '_dangling/indexUUID' but got %s"}`, r.URL.Path) + } + if u.Query().Get("accept_data_loss") == "" { + return http.StatusBadRequest, `{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"accept_data_loss must be set to true"}],"type":"illegal_argument_exception","reason":"accept_data_loss must be set to true"},"status":400}` + } + return 0, "" + } + + if r.Body != nil { + defer r.Body.Close() + } + switch r.Method { + case http.MethodGet: + if r.URL.Path != "/_dangling" { + w.WriteHeader(http.StatusNotImplemented) + io.Copy(w, strings.NewReader(fmt.Sprintf(`{"status": 501, "error": "Expected '_dangling' but got %s"}`, r.URL.Path))) + return + } + w.Write([]byte(`{"_nodes":{"total":1,"successful":1,"failed":0},"cluster_name":"docker-cluster","dangling_indices":[{"index_name":"test","index_uuid":"WaO0Mu-bSX6E7SdsuYU-yw","creation_date_millis":1694099652069,"node_ids":["xS9VXy4DTXmtO49gPaC3bw"]}]}`)) + case http.MethodPost: + if code, resp := testURL(r.URL); code != 0 { + w.WriteHeader(code) + io.Copy(w, strings.NewReader(resp)) + return + } + w.Write([]byte(`{"acknowledged": true}`)) + case http.MethodDelete: + if code, resp := testURL(r.URL); code != 0 { + w.WriteHeader(code) + io.Copy(w, strings.NewReader(resp)) + return + } + w.Write([]byte(`{"acknowledged": true}`)) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + io.Copy(w, strings.NewReader(fmt.Sprintf(`{"status": 405, "error": "Unexpected Method: %s"}`, r.Method))) + } + })) + + client, err := opensearchapi.NewClient(opensearchapi.Config{Client: opensearch.Config{Addresses: []string{ts.URL}}}) + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + type danglingTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []danglingTests + }{ + { + Name: "Import", + Tests: []danglingTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Dangling.Import( + nil, + opensearchapi.DanglingImportReq{ + IndexUUID: "indexUUID", + Params: opensearchapi.DanglingImportParams{AcceptDataLoss: opensearchapi.ToPointer(true)}, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Dangling.Import(nil, opensearchapi.DanglingImportReq{IndexUUID: "indexUUID"}) + }, + }, + }, + }, + { + Name: "Get", + Tests: []danglingTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Dangling.Get(nil, &opensearchapi.DanglingGetReq{}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Dangling.Get(nil, nil) + }, + }, + }, + }, + { + Name: "Delete", + Tests: []danglingTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Dangling.Delete( + nil, + opensearchapi.DanglingDeleteReq{ + IndexUUID: "indexUUID", + Params: opensearchapi.DanglingDeleteParams{AcceptDataLoss: opensearchapi.ToPointer(true)}, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Dangling.Delete(nil, opensearchapi.DanglingDeleteReq{IndexUUID: "indexUUID"}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + } + }) + } + }) + } + + t.Run("ValidateResponse", func(t *testing.T) { + t.Run("Get", func(t *testing.T) { + resp, err := client.Dangling.Get(nil, nil) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Delete", func(t *testing.T) { + resp, err := client.Dangling.Delete( + nil, + opensearchapi.DanglingDeleteReq{ + IndexUUID: "indexUUID", + Params: opensearchapi.DanglingDeleteParams{AcceptDataLoss: opensearchapi.ToPointer(true)}, + }, + ) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Import", func(t *testing.T) { + resp, err := client.Dangling.Import( + nil, + opensearchapi.DanglingImportReq{ + IndexUUID: "indexUUID", + Params: opensearchapi.DanglingImportParams{AcceptDataLoss: opensearchapi.ToPointer(true)}, + }, + ) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + }) +} diff --git a/opensearchapi/api_datastream-create-params.go b/opensearchapi/api_datastream-create-params.go new file mode 100644 index 000000000..8e13bf85f --- /dev/null +++ b/opensearchapi/api_datastream-create-params.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +// DataStreamCreateParams represents possible parameters for the DataStreamCreateReq +type DataStreamCreateParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DataStreamCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_datastream-create.go b/opensearchapi/api_datastream-create.go new file mode 100644 index 000000000..debfddfc9 --- /dev/null +++ b/opensearchapi/api_datastream-create.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DataStreamCreateReq represents possible options for the _data_stream create request +type DataStreamCreateReq struct { + DataStream string + + Header http.Header + Params DataStreamCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DataStreamCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_data_stream/%s", r.DataStream), + nil, + r.Params.get(), + r.Header, + ) +} + +// DataStreamCreateResp represents the returned struct of the _data_stream create response +type DataStreamCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DataStreamCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_datastream-delete-params.go b/opensearchapi/api_datastream-delete-params.go new file mode 100644 index 000000000..d666a15cb --- /dev/null +++ b/opensearchapi/api_datastream-delete-params.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "time" + +// DataStreamDeleteParams represents possible parameters for the DataStreamDeleteReq +type DataStreamDeleteParams struct { + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DataStreamDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_datastream-delete.go b/opensearchapi/api_datastream-delete.go new file mode 100644 index 000000000..10d3f8874 --- /dev/null +++ b/opensearchapi/api_datastream-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DataStreamDeleteReq represents possible options for the index _data_stream delete request +type DataStreamDeleteReq struct { + DataStream string + + Header http.Header + Params DataStreamDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DataStreamDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_data_stream/%s", r.DataStream), + nil, + r.Params.get(), + r.Header, + ) +} + +// DataStreamDeleteResp represents the returned struct of the _data_stream delete response +type DataStreamDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DataStreamDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_datastream-get-params.go b/opensearchapi/api_datastream-get-params.go new file mode 100644 index 000000000..3e4787869 --- /dev/null +++ b/opensearchapi/api_datastream-get-params.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "time" + +// DataStreamGetParams represents possible parameters for the DataStreamGetReq +type DataStreamGetParams struct { + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DataStreamGetParams) get() map[string]string { + params := make(map[string]string) + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_datastream-get.go b/opensearchapi/api_datastream-get.go new file mode 100644 index 000000000..ec880c4f7 --- /dev/null +++ b/opensearchapi/api_datastream-get.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DataStreamGetReq represents possible options for the _data_stream get request +type DataStreamGetReq struct { + DataStreams []string + + Header http.Header + Params DataStreamGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DataStreamGetReq) GetRequest() (*http.Request, error) { + dataStreams := strings.Join(r.DataStreams, ",") + + var path strings.Builder + path.Grow(len("/_data_stream/") + len(dataStreams)) + path.WriteString("/_data_stream") + if len(r.DataStreams) > 0 { + path.WriteString("/") + path.WriteString(dataStreams) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// DataStreamGetResp represents the returned struct of the _data_stream get response +type DataStreamGetResp struct { + DataStreams []DataStreamGetDetails `json:"data_streams"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DataStreamGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// DataStreamGetDetails is a sub type if DataStreamGetResp containing information about a data stream +type DataStreamGetDetails struct { + Name string `json:"name"` + TimestampField struct { + Name string `json:"name"` + } `json:"timestamp_field"` + Indices []DataStreamIndices `json:"indices"` + Generation int `json:"generation"` + Status string `json:"status"` + Template string `json:"template"` +} + +// DataStreamIndices is a sub type of DataStreamGetDetails containing information about an index +type DataStreamIndices struct { + Name string `json:"index_name"` + UUID string `json:"index_uuid"` +} diff --git a/opensearchapi/api_datastream-stats-params.go b/opensearchapi/api_datastream-stats-params.go new file mode 100644 index 000000000..55dc54033 --- /dev/null +++ b/opensearchapi/api_datastream-stats-params.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "time" + +// DataStreamStatsParams represents possible parameters for the DataStreamCreateReq +type DataStreamStatsParams struct { + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DataStreamStatsParams) get() map[string]string { + params := make(map[string]string) + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_datastream-stats.go b/opensearchapi/api_datastream-stats.go new file mode 100644 index 000000000..b3f9281ef --- /dev/null +++ b/opensearchapi/api_datastream-stats.go @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DataStreamStatsReq represents possible options for the _data_stream stats request +type DataStreamStatsReq struct { + DataStreams []string + + Header http.Header + Params DataStreamStatsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DataStreamStatsReq) GetRequest() (*http.Request, error) { + dataStreams := strings.Join(r.DataStreams, ",") + + var path strings.Builder + path.Grow(len("/_data_stream//_stats") + len(dataStreams)) + path.WriteString("/_data_stream/") + if len(r.DataStreams) > 0 { + path.WriteString(dataStreams) + path.WriteString("/") + } + path.WriteString("_stats") + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// DataStreamStatsResp represents the returned struct of the _data_stream stats response +type DataStreamStatsResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + DataStreamCount int `json:"data_stream_count"` + BackingIndices int `json:"backing_indices"` + TotalStoreSizeBytes int64 `json:"total_store_size_bytes"` + DataStreams []DataStreamStatsDetails `json:"data_streams"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DataStreamStatsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// DataStreamStatsDetails is a sub type of DataStreamStatsResp containing information about a data stream +type DataStreamStatsDetails struct { + DataStream string `json:"data_stream"` + BackingIndices int `json:"backing_indices"` + StoreSizeBytes int64 `json:"store_size_bytes"` + MaximumTimestamp int64 `json:"maximum_timestamp"` +} diff --git a/opensearchapi/api_datastream.go b/opensearchapi/api_datastream.go new file mode 100644 index 000000000..2942d1d6b --- /dev/null +++ b/opensearchapi/api_datastream.go @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type dataStreamClient struct { + apiClient *Client +} + +// Create executes a creade dataStream request with the required DataStreamCreateReq +func (c dataStreamClient) Create(ctx context.Context, req DataStreamCreateReq) (*DataStreamCreateResp, error) { + var ( + data DataStreamCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete dataStream request with the required DataStreamDeleteReq +func (c dataStreamClient) Delete(ctx context.Context, req DataStreamDeleteReq) (*DataStreamDeleteResp, error) { + var ( + data DataStreamDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get dataStream request with the optional DataStreamGetReq +func (c dataStreamClient) Get(ctx context.Context, req *DataStreamGetReq) (*DataStreamGetResp, error) { + if req == nil { + req = &DataStreamGetReq{} + } + + var ( + data DataStreamGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Stats executes a stats dataStream request with the optional DataStreamStatsReq +func (c dataStreamClient) Stats(ctx context.Context, req *DataStreamStatsReq) (*DataStreamStatsResp, error) { + if req == nil { + req = &DataStreamStatsReq{} + } + + var ( + data DataStreamStatsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_datastream_test.go b/opensearchapi/api_datastream_test.go new file mode 100644 index 000000000..77a4526f6 --- /dev/null +++ b/opensearchapi/api_datastream_test.go @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestDataStreamClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + dataStream := "data-stream-test" + + _, err = client.IndexTemplate.Create( + nil, + opensearchapi.IndexTemplateCreateReq{ + IndexTemplate: dataStream, + Body: strings.NewReader(`{"index_patterns":["data-stream-test"],"template":{"settings":{"index":{"number_of_replicas":"0"}}},"priority":60,"data_stream":{}}`), + }, + ) + require.Nil(t, err) + + type dataStreamTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []dataStreamTests + }{ + { + Name: "Create", + Tests: []dataStreamTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.DataStream.Create(nil, opensearchapi.DataStreamCreateReq{DataStream: dataStream}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.DataStream.Create(nil, opensearchapi.DataStreamCreateReq{DataStream: dataStream}) + }, + }, + }, + }, + { + Name: "Get", + Tests: []dataStreamTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.DataStream.Get(nil, &opensearchapi.DataStreamGetReq{DataStreams: []string{dataStream}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.DataStream.Get(nil, nil) + }, + }, + }, + }, + { + Name: "Stats", + Tests: []dataStreamTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.DataStream.Stats(nil, &opensearchapi.DataStreamStatsReq{DataStreams: []string{dataStream}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.DataStream.Stats(nil, nil) + }, + }, + }, + }, + { + Name: "Delete", + Tests: []dataStreamTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.DataStream.Delete(nil, opensearchapi.DataStreamDeleteReq{DataStream: dataStream}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.DataStream.Delete(nil, opensearchapi.DataStreamDeleteReq{DataStream: dataStream}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + }) + } + }) + } +} diff --git a/opensearchapi/api_document-create-params.go b/opensearchapi/api_document-create-params.go new file mode 100644 index 000000000..9c87e7354 --- /dev/null +++ b/opensearchapi/api_document-create-params.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// DocumentCreateParams represents possible parameters for the DocumentCreateReq +type DocumentCreateParams struct { + Pipeline string + Refresh string + Routing string + Timeout time.Duration + Version *int + VersionType string + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DocumentCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.Pipeline != "" { + params["pipeline"] = r.Pipeline + } + + if r.Refresh != "" { + params["refresh"] = r.Refresh + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_document-create.go b/opensearchapi/api_document-create.go new file mode 100644 index 000000000..a84ff29d5 --- /dev/null +++ b/opensearchapi/api_document-create.go @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DocumentCreateReq represents possible options for the //_create request +type DocumentCreateReq struct { + Index string + DocumentID string + + Body io.Reader + + Header http.Header + Params DocumentCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentCreateReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(10 + len(r.Index) + len(r.DocumentID)) + path.WriteString("/") + path.WriteString(r.Index) + path.WriteString("/_create/") + path.WriteString(r.DocumentID) + return opensearch.BuildRequest( + "PUT", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// DocumentCreateResp represents the returned struct of the /_doc response +type DocumentCreateResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Result string `json:"result"` + Type string `json:"_type"` // Deprecated field + ForcedRefresh bool `json:"forced_refresh"` + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_document-delete-params.go b/opensearchapi/api_document-delete-params.go new file mode 100644 index 000000000..69308d913 --- /dev/null +++ b/opensearchapi/api_document-delete-params.go @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// DocumentDeleteParams represents possible parameters for the DocumentDeleteReq +type DocumentDeleteParams struct { + IfPrimaryTerm *int + IfSeqNo *int + Refresh string + Routing string + Timeout time.Duration + Version *int + VersionType string + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DocumentDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.IfPrimaryTerm != nil { + params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10) + } + + if r.IfSeqNo != nil { + params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10) + } + + if r.Refresh != "" { + params["refresh"] = r.Refresh + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_document-delete.go b/opensearchapi/api_document-delete.go new file mode 100644 index 000000000..eb693f0b3 --- /dev/null +++ b/opensearchapi/api_document-delete.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DocumentDeleteReq represents possible options for the //_doc/ delete request +type DocumentDeleteReq struct { + Index string + DocumentID string + + Header http.Header + Params DocumentDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentDeleteReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(7 + len(r.Index) + len(r.DocumentID)) + path.WriteString("/") + path.WriteString(r.Index) + path.WriteString("/_doc/") + path.WriteString(r.DocumentID) + return opensearch.BuildRequest( + "DELETE", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// DocumentDeleteResp represents the returned struct of the //_doc/ response +type DocumentDeleteResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Result string `json:"result"` + Type string `json:"_type"` // Deprecated field + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_document-delete_by_query-params.go b/opensearchapi/api_document-delete_by_query-params.go new file mode 100644 index 000000000..b6b1a4f48 --- /dev/null +++ b/opensearchapi/api_document-delete_by_query-params.go @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// DocumentDeleteByQueryParams represents possible parameters for the DocumentDeleteByQueryReq +type DocumentDeleteByQueryParams struct { + AllowNoIndices *bool + Analyzer string + AnalyzeWildcard *bool + Conflicts string + DefaultOperator string + Df string + ExpandWildcards string + From *int + IgnoreUnavailable *bool + Lenient *bool + MaxDocs *int + Preference string + Query string + Refresh *bool + RequestCache *bool + RequestsPerSecond *int + Routing []string + Scroll time.Duration + ScrollSize *int + SearchTimeout time.Duration + SearchType string + Size *int + Slices interface{} + Sort []string + Source interface{} + SourceExcludes []string + SourceIncludes []string + Stats []string + TerminateAfter *int + Timeout time.Duration + Version *bool + WaitForActiveShards string + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DocumentDeleteByQueryParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.Conflicts != "" { + params["conflicts"] = r.Conflicts + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.From != nil { + params["from"] = strconv.FormatInt(int64(*r.From), 10) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.MaxDocs != nil { + params["max_docs"] = strconv.FormatInt(int64(*r.MaxDocs), 10) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Query != "" { + params["q"] = r.Query + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.RequestCache != nil { + params["request_cache"] = strconv.FormatBool(*r.RequestCache) + } + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if len(r.Routing) > 0 { + params["routing"] = strings.Join(r.Routing, ",") + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.ScrollSize != nil { + params["scroll_size"] = strconv.FormatInt(int64(*r.ScrollSize), 10) + } + + if r.SearchTimeout != 0 { + params["search_timeout"] = formatDuration(r.SearchTimeout) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.Size != nil { + params["size"] = strconv.FormatInt(int64(*r.Size), 10) + } + + if r.Slices != nil { + params["slices"] = fmt.Sprintf("%v", r.Slices) + } + + if len(r.Sort) > 0 { + params["sort"] = strings.Join(r.Sort, ",") + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.Stats) > 0 { + params["stats"] = strings.Join(r.Stats, ",") + } + + if r.TerminateAfter != nil { + params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Version != nil { + params["version"] = strconv.FormatBool(*r.Version) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_document-delete_by_query.go b/opensearchapi/api_document-delete_by_query.go new file mode 100644 index 000000000..1da1ba613 --- /dev/null +++ b/opensearchapi/api_document-delete_by_query.go @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DocumentDeleteByQueryReq represents possible options for the //_delete_by_query request +type DocumentDeleteByQueryReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params DocumentDeleteByQueryParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentDeleteByQueryReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_delete_by_query", strings.Join(r.Indices, ",")), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// DocumentDeleteByQueryResp represents the returned struct of the //_delete_by_query response +type DocumentDeleteByQueryResp struct { + Took int `json:"took"` + TimedOut bool `json:"timed_out"` + Total int `json:"total"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float32 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + Failures []json.RawMessage `json:"failures"` // Unknow struct, open an issue with an example response so we can add it + Task string `json:"task,omitempty"` // Needed when wait_for_completion is set to false + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentDeleteByQueryResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/internal/build/utils/chromatize.go b/opensearchapi/api_document-delete_by_query_rethrottle-params.go similarity index 62% rename from internal/build/utils/chromatize.go rename to opensearchapi/api_document-delete_by_query_rethrottle-params.go index 4db97497f..af978ec58 100644 --- a/internal/build/utils/chromatize.go +++ b/opensearchapi/api_document-delete_by_query_rethrottle-params.go @@ -24,40 +24,39 @@ // specific language governing permissions and limitations // under the License. -package utils +package opensearchapi import ( - "bytes" - "io" - "io/ioutil" - - "github.com/alecthomas/chroma/formatters" - "github.com/alecthomas/chroma/lexers" - "github.com/alecthomas/chroma/styles" + "strconv" ) -// Chromatize returns a syntax highlighted Go code. -// -func Chromatize(r io.Reader) (io.Reader, error) { - var b bytes.Buffer - lexer := lexers.Get("go") +// DocumentDeleteByQueryRethrottleParams represents possible parameters for the DocumentDeleteByQueryRethrottleReq +type DocumentDeleteByQueryRethrottleParams struct { + RequestsPerSecond *int + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DocumentDeleteByQueryRethrottleParams) get() map[string]string { + params := make(map[string]string) + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } - contents, err := ioutil.ReadAll(r) - if err != nil { - return nil, err + if r.Pretty { + params["pretty"] = "true" } - it, err := lexer.Tokenise(nil, string(contents)) - if err != nil { - return nil, err + if r.Human { + params["human"] = "true" } - style, _ := styles.Get("pygments").Builder().Build() - formatter := formatters.Get("terminal256") - err = formatter.Format(&b, style, it) - if err != nil { - return nil, err + if r.ErrorTrace { + params["error_trace"] = "true" } - return &b, nil + return params } diff --git a/opensearchapi/api_document-delete_by_query_rethrottle.go b/opensearchapi/api_document-delete_by_query_rethrottle.go new file mode 100644 index 000000000..88af1153f --- /dev/null +++ b/opensearchapi/api_document-delete_by_query_rethrottle.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DocumentDeleteByQueryRethrottleReq represents possible options for the /_delete_by_query//_rethrottle request +type DocumentDeleteByQueryRethrottleReq struct { + TaskID string + + Header http.Header + Params DocumentDeleteByQueryRethrottleParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentDeleteByQueryRethrottleReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_delete_by_query/%s/_rethrottle", r.TaskID), + nil, + r.Params.get(), + r.Header, + ) +} + +// DocumentDeleteByQueryRethrottleResp represents the returned struct of the /_delete_by_query//_rethrottle response +type DocumentDeleteByQueryRethrottleResp struct { + Nodes map[string]struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Tasks map[string]struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + Status struct { + Total int `json:"total"` + Updated int `json:"updated"` + Created int `json:"created"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float64 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + } `json:"status"` + Description string `json:"description"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers json.RawMessage `json:"headers"` + ResourceStats struct { + Average DocumentDeleteByQueryRethrottleResourceInfo `json:"average"` + Max DocumentDeleteByQueryRethrottleResourceInfo `json:"max"` + Min DocumentDeleteByQueryRethrottleResourceInfo `json:"min"` + Total DocumentDeleteByQueryRethrottleResourceInfo `json:"total"` + ThreadInfo struct { + ActiveThreads int `json:"active_threads"` + ThreadExecutions int `json:"thread_executions"` + } `json:"thread_info"` + } `json:"resource_stats"` + } `json:"tasks"` + } `json:"nodes"` + response *opensearch.Response +} + +// DocumentDeleteByQueryRethrottleResourceInfo is a sub type of DocumentDeleteByQueryRethrottleResp containing resource stats +type DocumentDeleteByQueryRethrottleResourceInfo struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentDeleteByQueryRethrottleResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_document-exists-params.go b/opensearchapi/api_document-exists-params.go new file mode 100644 index 000000000..0ff9011c2 --- /dev/null +++ b/opensearchapi/api_document-exists-params.go @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentExistsParams represents possible parameters for the DocumentExistsReq +type DocumentExistsParams struct { + Preference string + Realtime *bool + Refresh *bool + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + StoredFields []string + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DocumentExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.StoredFields) > 0 { + params["stored_fields"] = strings.Join(r.StoredFields, ",") + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_document-exists.go b/opensearchapi/api_document-exists.go new file mode 100644 index 000000000..9490ba3ff --- /dev/null +++ b/opensearchapi/api_document-exists.go @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DocumentExistsReq represents possible options for the document exists request +type DocumentExistsReq struct { + Index string + DocumentID string + + Header http.Header + Params DocumentExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentExistsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("/%s/_doc/%s", r.Index, r.DocumentID), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/opensearchapi/api_document-exists_source-params.go b/opensearchapi/api_document-exists_source-params.go new file mode 100644 index 000000000..965c200f5 --- /dev/null +++ b/opensearchapi/api_document-exists_source-params.go @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentExistsSourceParams represents possible parameters for the DocumentExistsSourceReq +type DocumentExistsSourceParams struct { + Preference string + Realtime *bool + Refresh *bool + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DocumentExistsSourceParams) get() map[string]string { + params := make(map[string]string) + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_document-exists_source.go b/opensearchapi/api_document-exists_source.go new file mode 100644 index 000000000..7accfe413 --- /dev/null +++ b/opensearchapi/api_document-exists_source.go @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DocumentExistsSourceReq represents possible options for the _source exists request +type DocumentExistsSourceReq struct { + Index string + DocumentID string + + Header http.Header + Params DocumentExistsSourceParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentExistsSourceReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("/%s/_source/%s", r.Index, r.DocumentID), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/opensearchapi/api_document-explain-params.go b/opensearchapi/api_document-explain-params.go new file mode 100644 index 000000000..0dafc9c47 --- /dev/null +++ b/opensearchapi/api_document-explain-params.go @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentExplainParams represents possible parameters for the DocumentExplainReq +type DocumentExplainParams struct { + Analyzer string + AnalyzeWildcard *bool + DefaultOperator string + Df string + Lenient *bool + Preference string + Query string + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + StoredFields []string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DocumentExplainParams) get() map[string]string { + params := make(map[string]string) + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Query != "" { + params["q"] = r.Query + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.StoredFields) > 0 { + params["stored_fields"] = strings.Join(r.StoredFields, ",") + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_document-explain.go b/opensearchapi/api_document-explain.go new file mode 100644 index 000000000..0ef4c15a5 --- /dev/null +++ b/opensearchapi/api_document-explain.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DocumentExplainReq represents possible options for the //_explain/ request +type DocumentExplainReq struct { + Index string + DocumentID string + + Body io.Reader + + Header http.Header + Params DocumentExplainParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentExplainReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_explain/%s", r.Index, r.DocumentID), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// DocumentExplainResp represents the returned struct of the //_explain/ response +type DocumentExplainResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Type string `json:"_type"` // Deprecated field + Matched bool `json:"matched"` + Explanation DocumentExplainDetails `json:"explanation"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentExplainResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// DocumentExplainDetails is a sub type of DocumentExplainResp containing information about why a query does what it does +type DocumentExplainDetails struct { + Value float64 `json:"value"` + Description string `json:"description"` + Details []DocumentExplainDetails `json:"details"` +} diff --git a/opensearchapi/api_document-get-params.go b/opensearchapi/api_document-get-params.go new file mode 100644 index 000000000..7406c5bc8 --- /dev/null +++ b/opensearchapi/api_document-get-params.go @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentGetParams represents possible parameters for the DocumentGetReq +type DocumentGetParams struct { + Preference string + Realtime *bool + Refresh *bool + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + StoredFields []string + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DocumentGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.StoredFields) > 0 { + params["stored_fields"] = strings.Join(r.StoredFields, ",") + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_document-get.go b/opensearchapi/api_document-get.go new file mode 100644 index 000000000..12f86c8a3 --- /dev/null +++ b/opensearchapi/api_document-get.go @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DocumentGetReq represents possible options for the //_doc/ get request +type DocumentGetReq struct { + Index string + DocumentID string + + Header http.Header + Params DocumentGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/%s/_doc/%s", r.Index, r.DocumentID), + nil, + r.Params.get(), + r.Header, + ) +} + +// DocumentGetResp represents the returned struct of the //_doc/ get response +type DocumentGetResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + Found bool `json:"found"` + Type string `json:"_type"` // Deprecated field + Source json.RawMessage `json:"_source"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_document-source-params.go b/opensearchapi/api_document-source-params.go new file mode 100644 index 000000000..566d5b098 --- /dev/null +++ b/opensearchapi/api_document-source-params.go @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// DocumentSourceParams represents possible parameters for the DocumentSourceReq +type DocumentSourceParams struct { + Preference string + Realtime *bool + Refresh *bool + Routing string + // Deprecated: This parameter is similar to SourceIncludes, please use that instead. + Source interface{} + SourceExcludes []string + SourceIncludes []string + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r DocumentSourceParams) get() map[string]string { + params := make(map[string]string) + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_document-source.go b/opensearchapi/api_document-source.go new file mode 100644 index 000000000..52aed15fb --- /dev/null +++ b/opensearchapi/api_document-source.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// DocumentSourceReq represents possible options for the //_source/ get request +type DocumentSourceReq struct { + Index string + DocumentID string + + Header http.Header + Params DocumentSourceParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r DocumentSourceReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/%s/_source/%s", r.Index, r.DocumentID), + nil, + r.Params.get(), + r.Header, + ) +} + +// DocumentSourceResp represents the returned struct of the //_source/ get response +type DocumentSourceResp struct { + Source json.RawMessage + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r DocumentSourceResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_document.go b/opensearchapi/api_document.go new file mode 100644 index 000000000..56f4067da --- /dev/null +++ b/opensearchapi/api_document.go @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v2" +) + +type documentClient struct { + apiClient *Client +} + +// Create executes a creade document request with the required DocumentCreateReq +func (c documentClient) Create(ctx context.Context, req DocumentCreateReq) (*DocumentCreateResp, error) { + var ( + data DocumentCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete document request with the required DocumentDeleteReq +func (c documentClient) Delete(ctx context.Context, req DocumentDeleteReq) (*DocumentDeleteResp, error) { + var ( + data DocumentDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// DeleteByQuery executes a delete by query request with the required DocumentDeleteByQueryReq +func (c documentClient) DeleteByQuery(ctx context.Context, req DocumentDeleteByQueryReq) (*DocumentDeleteByQueryResp, error) { + var ( + data DocumentDeleteByQueryResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// DeleteByQueryRethrottle executes a delete by query rethrottle request with the optional DocumentDeleteByQueryRethrottleReq +func (c documentClient) DeleteByQueryRethrottle( + ctx context.Context, + req DocumentDeleteByQueryRethrottleReq, +) (*DocumentDeleteByQueryRethrottleResp, error) { + var ( + data DocumentDeleteByQueryRethrottleResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes a exists document request with the required DocumentExistsReq +func (c documentClient) Exists(ctx context.Context, req DocumentExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} + +// ExistsSource executes a exists source request with the required DocumentExistsSourceReq +func (c documentClient) ExistsSource(ctx context.Context, req DocumentExistsSourceReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} + +// Explain executes an explain document request with the required DocumentExplainReq +func (c documentClient) Explain(ctx context.Context, req DocumentExplainReq) (*DocumentExplainResp, error) { + var ( + data DocumentExplainResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a //_doc/ request with the required DocumentGetReq +func (c documentClient) Get(ctx context.Context, req DocumentGetReq) (*DocumentGetResp, error) { + var ( + data DocumentGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Source executes a //_source/ request with the required DocumentSourceReq +func (c documentClient) Source(ctx context.Context, req DocumentSourceReq) (*DocumentSourceResp, error) { + var ( + data DocumentSourceResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Source); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_document_test.go b/opensearchapi/api_document_test.go new file mode 100644 index 000000000..e5d2b9032 --- /dev/null +++ b/opensearchapi/api_document_test.go @@ -0,0 +1,396 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "context" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" + "github.com/opensearch-project/opensearch-go/v2/opensearchutil" +) + +func TestDocumentClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + index := "test-document" + documentID := "test" + + t.Cleanup(func() { client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{index}}) }) + + type docIndexPrep struct { + DocCount int + Body string + } + + type documentTests struct { + Name string + IndexPrepare *docIndexPrep + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []documentTests + }{ + { + Name: "Create", + Tests: []documentTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: index, + Body: strings.NewReader(`{"foo": "bar"}`), + DocumentID: documentID, + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: index, + Body: strings.NewReader("{}"), + DocumentID: documentID, + }, + ) + }, + }, + }, + }, + { + Name: "Exists", + Tests: []documentTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = client.Document.Exists(nil, opensearchapi.DocumentExistsReq{Index: index, DocumentID: documentID}) + return resp, err + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = failingClient.Document.Exists(nil, opensearchapi.DocumentExistsReq{Index: index, DocumentID: documentID}) + return resp, err + }, + }, + }, + }, + { + Name: "ExistsSource", + Tests: []documentTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = client.Document.ExistsSource(nil, opensearchapi.DocumentExistsSourceReq{Index: index, DocumentID: documentID}) + return resp, err + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = failingClient.Document.ExistsSource(nil, opensearchapi.DocumentExistsSourceReq{Index: index, DocumentID: documentID}) + return resp, err + }, + }, + }, + }, + { + Name: "Get", + Tests: []documentTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Document.Get( + nil, + opensearchapi.DocumentGetReq{ + Index: index, + DocumentID: documentID, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Document.Get( + nil, + opensearchapi.DocumentGetReq{ + Index: index, + DocumentID: documentID, + }, + ) + }, + }, + }, + }, + { + Name: "Explain", + Tests: []documentTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Document.Explain( + nil, + opensearchapi.DocumentExplainReq{ + Index: index, + DocumentID: documentID, + Body: strings.NewReader(`{"query":{"term":{"foo":{"value":"bar"}}}}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Document.Explain( + nil, + opensearchapi.DocumentExplainReq{ + Index: index, + DocumentID: documentID, + Body: strings.NewReader(``), + }, + ) + }, + }, + }, + }, + { + Name: "Source", + Tests: []documentTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Document.Source( + nil, + opensearchapi.DocumentSourceReq{ + Index: index, + DocumentID: documentID, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Document.Source( + nil, + opensearchapi.DocumentSourceReq{ + Index: index, + DocumentID: documentID, + }, + ) + }, + }, + }, + }, + { + Name: "Delete", + Tests: []documentTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Document.Delete( + nil, + opensearchapi.DocumentDeleteReq{ + Index: index, + DocumentID: documentID, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Document.Delete( + nil, + opensearchapi.DocumentDeleteReq{ + Index: index, + DocumentID: documentID, + }, + ) + }, + }, + }, + }, + { + Name: "DeleteByQuery", + Tests: []documentTests{ + { + Name: "with request", + IndexPrepare: &docIndexPrep{DocCount: 100, Body: `{"title":"bar"}`}, + Results: func() (osapitest.Response, error) { + return client.Document.DeleteByQuery( + nil, + opensearchapi.DocumentDeleteByQueryReq{ + Indices: []string{index}, + Body: strings.NewReader(`{"query":{"match":{"title":"bar"}}}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Document.DeleteByQuery( + nil, + opensearchapi.DocumentDeleteByQueryReq{ + Indices: []string{index}, + Body: strings.NewReader(`{"query":{"match":{"title":"bar"}}}`), + }, + ) + }, + }, + }, + }, + { + Name: "DeleteByQueryRethrottle", + Tests: []documentTests{ + { + Name: "with request", + IndexPrepare: &docIndexPrep{DocCount: 10000, Body: `{"title":"foo"}`}, + Results: func() (osapitest.Response, error) { + delResp, err := client.Document.DeleteByQuery( + nil, + opensearchapi.DocumentDeleteByQueryReq{ + Indices: []string{index}, + Body: strings.NewReader(`{"query":{"match":{"title":"foo"}}}`), + Params: opensearchapi.DocumentDeleteByQueryParams{WaitForCompletion: opensearchapi.ToPointer(false)}, + }, + ) + if err != nil { + return delResp, err + } + return client.Document.DeleteByQueryRethrottle( + nil, + opensearchapi.DocumentDeleteByQueryRethrottleReq{ + TaskID: delResp.Task, + Params: opensearchapi.DocumentDeleteByQueryRethrottleParams{RequestsPerSecond: opensearchapi.ToPointer(50)}, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Document.DeleteByQueryRethrottle( + nil, + opensearchapi.DocumentDeleteByQueryRethrottleReq{ + TaskID: "some-task-id", + Params: opensearchapi.DocumentDeleteByQueryRethrottleParams{RequestsPerSecond: opensearchapi.ToPointer(50)}, + }, + ) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + if testCase.IndexPrepare != nil { + bi, _ := opensearchutil.NewBulkIndexer(opensearchutil.BulkIndexerConfig{ + Index: index, + Client: client, + ErrorTrace: true, + Human: true, + Pretty: true, + }) + for i := 1; i <= testCase.IndexPrepare.DocCount; i++ { + err := bi.Add(context.Background(), opensearchutil.BulkIndexerItem{ + Index: index, + Action: "index", + DocumentID: strconv.Itoa(i), + Body: strings.NewReader(testCase.IndexPrepare.Body), + }) + if err != nil { + t.Fatalf("Unexpected error: %s", err) + } + } + + if err := bi.Close(context.Background()); err != nil { + t.Errorf("Unexpected error: %s", err) + } + } + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + if !strings.Contains(value.Name, "Exists") && value.Name != "Source" { + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + } + }) + } + }) + } + t.Run("ValidateResponse", func(t *testing.T) { + t.Run("Source", func(t *testing.T) { + _, err := client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: index, + Body: strings.NewReader(`{"foo": "bar"}`), + DocumentID: documentID, + }, + ) + require.Nil(t, err) + res, err := client.Document.Source( + nil, + opensearchapi.DocumentSourceReq{ + Index: index, + DocumentID: documentID, + }, + ) + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + osapitest.CompareRawJSONwithParsedJSON(t, res.Source, res.Inspect().Response) + }) + }) +} diff --git a/opensearchapi/api_index-params.go b/opensearchapi/api_index-params.go new file mode 100644 index 000000000..97fb6313d --- /dev/null +++ b/opensearchapi/api_index-params.go @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndexParams represents possible parameters for the IndexReq +type IndexParams struct { + IfPrimaryTerm *int + IfSeqNo *int + OpType string + Pipeline string + Refresh string + RequireAlias *bool + Routing string + Timeout time.Duration + Version *int + VersionType string + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndexParams) get() map[string]string { + params := make(map[string]string) + + if r.IfPrimaryTerm != nil { + params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10) + } + + if r.IfSeqNo != nil { + params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10) + } + + if r.OpType != "" { + params["op_type"] = r.OpType + } + + if r.Pipeline != "" { + params["pipeline"] = r.Pipeline + } + + if r.Refresh != "" { + params["refresh"] = r.Refresh + } + + if r.RequireAlias != nil { + params["require_alias"] = strconv.FormatBool(*r.RequireAlias) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_index.go b/opensearchapi/api_index.go new file mode 100644 index 000000000..355cacdcb --- /dev/null +++ b/opensearchapi/api_index.go @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// Index executes a /_doc request with the given IndexReq +func (c Client) Index(ctx context.Context, req IndexReq) (*IndexResp, error) { + var ( + data IndexResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// IndexReq represents possible options for the /_doc request +type IndexReq struct { + Index string + DocumentID string + Body io.Reader + Header http.Header + Params IndexParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexReq) GetRequest() (*http.Request, error) { + var method, path string + + if r.DocumentID != "" { + method = "PUT" + path = fmt.Sprintf("/%s/_doc/%s", r.Index, r.DocumentID) + } else { + method = "POST" + path = fmt.Sprintf("/%s/_doc", r.Index) + } + + return opensearch.BuildRequest( + method, + path, + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndexResp represents the returned struct of the /_doc response +type IndexResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Result string `json:"result"` + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + Type string `json:"_type"` // Deprecated field + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_index_template-create-params.go b/opensearchapi/api_index_template-create-params.go new file mode 100644 index 000000000..9eb9f4c99 --- /dev/null +++ b/opensearchapi/api_index_template-create-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndexTemplateCreateParams represents possible parameters for the IndexTemplateCreateReq +type IndexTemplateCreateParams struct { + Cause string + Create *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndexTemplateCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.Cause != "" { + params["cause"] = r.Cause + } + + if r.Create != nil { + params["create"] = strconv.FormatBool(*r.Create) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_index_template-create.go b/opensearchapi/api_index_template-create.go new file mode 100644 index 000000000..dc17baffc --- /dev/null +++ b/opensearchapi/api_index_template-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndexTemplateCreateReq represents possible options for the index create request +type IndexTemplateCreateReq struct { + IndexTemplate string + + Body io.Reader + + Header http.Header + Params IndexTemplateCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_index_template/%s", r.IndexTemplate), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndexTemplateCreateResp represents the returned struct of the index create response +type IndexTemplateCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexTemplateCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_index_template-delete-params.go b/opensearchapi/api_index_template-delete-params.go new file mode 100644 index 000000000..d337ed6fa --- /dev/null +++ b/opensearchapi/api_index_template-delete-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// IndexTemplateDeleteParams represents possible parameters for the IndexTemplateDeleteReq +type IndexTemplateDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndexTemplateDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_index_template-delete.go b/opensearchapi/api_index_template-delete.go new file mode 100644 index 000000000..fb3336396 --- /dev/null +++ b/opensearchapi/api_index_template-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndexTemplateDeleteReq represents possible options for the index create request +type IndexTemplateDeleteReq struct { + IndexTemplate string + + Header http.Header + Params IndexTemplateDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_index_template/%s", r.IndexTemplate), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndexTemplateDeleteResp represents the returned struct of the index create response +type IndexTemplateDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexTemplateDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_index_template-exists-params.go b/opensearchapi/api_index_template-exists-params.go new file mode 100644 index 000000000..95a3c7179 --- /dev/null +++ b/opensearchapi/api_index_template-exists-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndexTemplateExistsParams represents possible parameters for the IndexTemplateExistsReq +type IndexTemplateExistsParams struct { + FlatSettings *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndexTemplateExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_index_template-exists.go b/opensearchapi/api_index_template-exists.go new file mode 100644 index 000000000..5a290200e --- /dev/null +++ b/opensearchapi/api_index_template-exists.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndexTemplateExistsReq represents possible options for the index create request +type IndexTemplateExistsReq struct { + IndexTemplate string + + Header http.Header + Params IndexTemplateExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateExistsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("/_index_template/%s", r.IndexTemplate), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/opensearchapi/api_index_template-get-params.go b/opensearchapi/api_index_template-get-params.go new file mode 100644 index 000000000..bea907b77 --- /dev/null +++ b/opensearchapi/api_index_template-get-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndexTemplateGetParams represents possible parameters for the IndexTemplateGetReq +type IndexTemplateGetParams struct { + FlatSettings *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndexTemplateGetParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_index_template-get.go b/opensearchapi/api_index_template-get.go new file mode 100644 index 000000000..a0ce8c312 --- /dev/null +++ b/opensearchapi/api_index_template-get.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndexTemplateGetReq represents possible options for the index create request +type IndexTemplateGetReq struct { + IndexTemplates []string + + Header http.Header + Params IndexTemplateGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_index_template/%s", strings.Join(r.IndexTemplates, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndexTemplateGetResp represents the returned struct of the index create response +type IndexTemplateGetResp struct { + IndexTemplates []IndexTemplateGetDetails `json:"index_templates"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexTemplateGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// IndexTemplateGetDetails is a sub type of IndexTemplateGetResp containing information about an index template +type IndexTemplateGetDetails struct { + Name string `json:"name"` + IndexTemplate struct { + IndexPatterns []string `json:"index_patterns"` + Template struct { + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` + } `json:"template"` + ComposedOf []string `json:"composed_of"` + Priority int `json:"priority"` + Version int `json:"version"` + DataStream json.RawMessage `json:"data_stream"` + } `json:"index_template"` +} diff --git a/opensearchapi/api_index_template-simulate-params.go b/opensearchapi/api_index_template-simulate-params.go new file mode 100644 index 000000000..488c78ccb --- /dev/null +++ b/opensearchapi/api_index_template-simulate-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndexTemplateSimulateParams represents possible parameters for the IndexTemplateSimulateReq +type IndexTemplateSimulateParams struct { + Cause string + Create *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndexTemplateSimulateParams) get() map[string]string { + params := make(map[string]string) + + if r.Cause != "" { + params["cause"] = r.Cause + } + + if r.Create != nil { + params["create"] = strconv.FormatBool(*r.Create) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_index_template-simulate.go b/opensearchapi/api_index_template-simulate.go new file mode 100644 index 000000000..1aae13c63 --- /dev/null +++ b/opensearchapi/api_index_template-simulate.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndexTemplateSimulateReq represents possible options for the index create request +type IndexTemplateSimulateReq struct { + IndexTemplate string + + Body io.Reader + + Header http.Header + Params IndexTemplateSimulateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateSimulateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_index_template/_simulate/%s", r.IndexTemplate), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndexTemplateSimulateResp represents the returned struct of the index create response +type IndexTemplateSimulateResp struct { + Template struct { + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` + } `json:"template"` + Overlapping []struct { + Name string `json:"name"` + IndexPatterns []string `json:"index_patterns"` + } `json:"overlapping"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexTemplateSimulateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_index_template-simulate_index-params.go b/opensearchapi/api_index_template-simulate_index-params.go new file mode 100644 index 000000000..c437a908e --- /dev/null +++ b/opensearchapi/api_index_template-simulate_index-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndexTemplateSimulateIndexParams represents possible parameters for the IndexTemplateSimulateIndexReq +type IndexTemplateSimulateIndexParams struct { + Cause string + Create *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndexTemplateSimulateIndexParams) get() map[string]string { + params := make(map[string]string) + + if r.Cause != "" { + params["cause"] = r.Cause + } + + if r.Create != nil { + params["create"] = strconv.FormatBool(*r.Create) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_index_template-simulate_index.go b/opensearchapi/api_index_template-simulate_index.go new file mode 100644 index 000000000..3c1dee501 --- /dev/null +++ b/opensearchapi/api_index_template-simulate_index.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndexTemplateSimulateIndexReq represents possible options for the index create request +type IndexTemplateSimulateIndexReq struct { + Index string + + Body io.Reader + + Header http.Header + Params IndexTemplateSimulateIndexParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndexTemplateSimulateIndexReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_index_template/_simulate_index/%s", r.Index), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndexTemplateSimulateIndexResp represents the returned struct of the index create response +type IndexTemplateSimulateIndexResp struct { + Template struct { + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` + } `json:"template"` + Overlapping []struct { + Name string `json:"name"` + IndexPatterns []string `json:"index_patterns"` + } `json:"overlapping"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndexTemplateSimulateIndexResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_index_template.go b/opensearchapi/api_index_template.go new file mode 100644 index 000000000..25f0a9fd2 --- /dev/null +++ b/opensearchapi/api_index_template.go @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v2" +) + +type indexTemplateClient struct { + apiClient *Client +} + +// Create executes a creade indexTemplate request with the required IndexTemplateCreateReq +func (c indexTemplateClient) Create(ctx context.Context, req IndexTemplateCreateReq) (*IndexTemplateCreateResp, error) { + var ( + data IndexTemplateCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete indexTemplate request with the required IndexTemplateDeleteReq +func (c indexTemplateClient) Delete(ctx context.Context, req IndexTemplateDeleteReq) (*IndexTemplateDeleteResp, error) { + var ( + data IndexTemplateDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get indexTemplate request with the optional IndexTemplateGetReq +func (c indexTemplateClient) Get(ctx context.Context, req *IndexTemplateGetReq) (*IndexTemplateGetResp, error) { + if req == nil { + req = &IndexTemplateGetReq{} + } + + var ( + data IndexTemplateGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes a exists indexTemplate request with the required IndexTemplatExistsReq +func (c indexTemplateClient) Exists(ctx context.Context, req IndexTemplateExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} + +// Simulate executes a _simulate indexTemplate request with the required IndexTemplateSimulateReq +func (c indexTemplateClient) Simulate(ctx context.Context, req IndexTemplateSimulateReq) (*IndexTemplateSimulateResp, error) { + var ( + data IndexTemplateSimulateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// SimulateIndex executes a _simulate_index indexTemplate request with the required IndexTemplateSimulateIndexReq +func (c indexTemplateClient) SimulateIndex( + ctx context.Context, + req IndexTemplateSimulateIndexReq, +) (*IndexTemplateSimulateIndexResp, error) { + var ( + data IndexTemplateSimulateIndexResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_index_template_test.go b/opensearchapi/api_index_template_test.go new file mode 100644 index 000000000..248240861 --- /dev/null +++ b/opensearchapi/api_index_template_test.go @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestIndexTemplateClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + indexTemplate := "index-template-test" + + type indexTemplateTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []indexTemplateTests + }{ + { + Name: "Create", + Tests: []indexTemplateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.IndexTemplate.Create( + nil, + opensearchapi.IndexTemplateCreateReq{ + IndexTemplate: indexTemplate, + Body: strings.NewReader(`{"index_patterns":["index-template*"],"priority":60}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.IndexTemplate.Create(nil, opensearchapi.IndexTemplateCreateReq{IndexTemplate: indexTemplate}) + }, + }, + }, + }, + { + Name: "Get", + Tests: []indexTemplateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.IndexTemplate.Get(nil, &opensearchapi.IndexTemplateGetReq{IndexTemplates: []string{indexTemplate}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.IndexTemplate.Get(nil, nil) + }, + }, + }, + }, + { + Name: "Exists", + Tests: []indexTemplateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = client.IndexTemplate.Exists(nil, opensearchapi.IndexTemplateExistsReq{IndexTemplate: indexTemplate}) + return resp, err + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = failingClient.IndexTemplate.Exists(nil, opensearchapi.IndexTemplateExistsReq{IndexTemplate: indexTemplate}) + return resp, err + }, + }, + }, + }, + { + Name: "Simulate", + Tests: []indexTemplateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.IndexTemplate.Simulate( + nil, + opensearchapi.IndexTemplateSimulateReq{ + IndexTemplate: indexTemplate, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.IndexTemplate.Simulate(nil, opensearchapi.IndexTemplateSimulateReq{}) + }, + }, + }, + }, + { + Name: "SimulateIndex", + Tests: []indexTemplateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.IndexTemplate.SimulateIndex( + nil, + opensearchapi.IndexTemplateSimulateIndexReq{ + Index: indexTemplate, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.IndexTemplate.SimulateIndex(nil, opensearchapi.IndexTemplateSimulateIndexReq{}) + }, + }, + }, + }, + { + Name: "Delete", + Tests: []indexTemplateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.IndexTemplate.Delete(nil, opensearchapi.IndexTemplateDeleteReq{IndexTemplate: indexTemplate}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.IndexTemplate.Delete(nil, opensearchapi.IndexTemplateDeleteReq{IndexTemplate: indexTemplate}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + if value.Name != "Exists" { + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + } + }) + } + }) + } +} diff --git a/opensearchapi/api_index_test.go b/opensearchapi/api_index_test.go new file mode 100644 index 000000000..df657f92b --- /dev/null +++ b/opensearchapi/api_index_test.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "errors" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestIndexClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + index := "test-index-test" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{index}}) + }) + + t.Run("Request Empty", func(t *testing.T) { + resp, err := client.Index(nil, opensearchapi.IndexReq{}) + assert.NotNil(t, err) + var osError opensearchapi.StringError + ok := errors.As(err, &osError) + assert.Equal(t, http.StatusMethodNotAllowed, osError.Status) + assert.Contains(t, osError.Err, "Incorrect HTTP method for uri") + assert.True(t, ok) + assert.NotNil(t, resp) + assert.NotNil(t, resp.Inspect()) + }) + + t.Run("Request Index only", func(t *testing.T) { + resp, err := client.Index(nil, opensearchapi.IndexReq{Index: index}) + assert.NotNil(t, err) + var osError opensearchapi.Error + ok := errors.As(err, &osError) + assert.True(t, ok) + assert.Equal(t, "parse_exception", osError.Err.Type) + assert.Equal(t, "request body is required", osError.Err.Reason) + assert.NotNil(t, resp) + assert.NotNil(t, resp.Inspect()) + }) + + t.Run("Request with DocID", func(t *testing.T) { + for _, result := range []string{"created", "updated"} { + body := strings.NewReader("{}") + resp, err := client.Index(nil, opensearchapi.IndexReq{Index: index, Body: body, DocumentID: "test"}) + require.Nil(t, err) + require.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + assert.Equal(t, result, resp.Result) + } + }) + + t.Run("Request without DocID", func(t *testing.T) { + body := strings.NewReader("{}") + resp, err := client.Index(nil, opensearchapi.IndexReq{Index: index, Body: body}) + require.Nil(t, err) + require.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + assert.Equal(t, index, resp.Index) + assert.Equal(t, "created", resp.Result) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.Index(nil, opensearchapi.IndexReq{Index: index}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_indices-alias-params.go b/opensearchapi/api_indices-alias-params.go new file mode 100644 index 000000000..eafa53938 --- /dev/null +++ b/opensearchapi/api_indices-alias-params.go @@ -0,0 +1,206 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// AliasDeleteParams represents possible parameters for the AliasDeleteReq +type AliasDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r AliasDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} + +// AliasGetParams represents possible parameters for the AliasGetReq +type AliasGetParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Local *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r AliasGetParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} + +// AliasPutParams represents possible parameters for the AliasPutReq +type AliasPutParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r AliasPutParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} + +// AliasExistsParams represents possible parameters for the AliasExistsReq +type AliasExistsParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Local *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r AliasExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-alias.go b/opensearchapi/api_indices-alias.go new file mode 100644 index 000000000..da014f841 --- /dev/null +++ b/opensearchapi/api_indices-alias.go @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +type aliasClient struct { + apiClient *Client +} + +// Delete executes a delete alias request with the required AliasDeleteReq +func (c aliasClient) Delete(ctx context.Context, req AliasDeleteReq) (*AliasDeleteResp, error) { + var ( + data AliasDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get alias request with the required AliasGetReq +func (c aliasClient) Get(ctx context.Context, req AliasGetReq) (*AliasGetResp, error) { + var ( + data AliasGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Put executes a put alias request with the required AliasPutReq +func (c aliasClient) Put(ctx context.Context, req AliasPutReq) (*AliasPutResp, error) { + var ( + data AliasPutResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes an exists alias request with the required AliasExistsReq +func (c aliasClient) Exists(ctx context.Context, req AliasExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} + +// AliasDeleteReq represents possible options for the alias delete request +type AliasDeleteReq struct { + Indices []string + Alias []string + + Header http.Header + Params AliasDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r AliasDeleteReq) GetRequest() (*http.Request, error) { + aliases := strings.Join(r.Alias, ",") + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(aliases)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_alias/") + path.WriteString(aliases) + return opensearch.BuildRequest( + "DELETE", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// AliasDeleteResp represents the returned struct of the alias delete response +type AliasDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r AliasDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// AliasGetReq represents possible options for the alias get request +type AliasGetReq struct { + Indices []string + Alias []string + + Header http.Header + Params AliasGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r AliasGetReq) GetRequest() (*http.Request, error) { + aliases := strings.Join(r.Alias, ",") + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(aliases)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_alias/") + path.WriteString(aliases) + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// AliasGetResp represents the returned struct of the alias get response +type AliasGetResp struct { + Indices map[string]struct { + Aliases map[string]json.RawMessage `json:"aliases"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r AliasGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// AliasPutReq represents possible options for the alias put request +type AliasPutReq struct { + Indices []string + Alias string + + Header http.Header + Params AliasPutParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r AliasPutReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(r.Alias)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_alias/") + path.WriteString(r.Alias) + return opensearch.BuildRequest( + "PUT", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// AliasPutResp represents the returned struct of the alias put response +type AliasPutResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r AliasPutResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// AliasExistsReq represents possible options for the alias exists request +type AliasExistsReq struct { + Indices []string + Alias []string + + Header http.Header + Params AliasExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r AliasExistsReq) GetRequest() (*http.Request, error) { + aliases := strings.Join(r.Alias, ",") + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(r.Alias)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_alias/") + path.WriteString(aliases) + return opensearch.BuildRequest( + "HEAD", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/opensearchapi/api_indices-analyze-params.go b/opensearchapi/api_indices-analyze-params.go new file mode 100644 index 000000000..f1052ba01 --- /dev/null +++ b/opensearchapi/api_indices-analyze-params.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +// IndicesAnalyzeParams represents possible parameters for the IndicesAnalyzeReq +type IndicesAnalyzeParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesAnalyzeParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-analyze.go b/opensearchapi/api_indices-analyze.go new file mode 100644 index 000000000..5568029b4 --- /dev/null +++ b/opensearchapi/api_indices-analyze.go @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "bytes" + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesAnalyzeReq represents possible options for the /_analyze request +type IndicesAnalyzeReq struct { + Index string + Body IndicesAnalyzeBody + + Header http.Header + Params IndicesAnalyzeParams +} + +// IndicesAnalyzeBody represents the request body for the indices analyze request +type IndicesAnalyzeBody struct { + Analyzer string `json:"analyzer,omitempty"` + Attributes []string `json:"attributes,omitempty"` + CharFilter []string `json:"char_filter,omitempty"` + Explain bool `json:"explain,omitempty"` + Field string `json:"field,omitempty"` + Filter []string `json:"filter,omitempty"` + Normalizer string `json:"normalizer,omitempty"` + Text []string `json:"text"` + Tokenizer string `json:"tokenizer,omitempty"` +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesAnalyzeReq) GetRequest() (*http.Request, error) { + body, err := json.Marshal(r.Body) + if err != nil { + return nil, err + } + + var path strings.Builder + path.Grow(10 + len(r.Index)) + if len(r.Index) != 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + path.WriteString("/_analyze") + return opensearch.BuildRequest( + "GET", + path.String(), + bytes.NewReader(body), + r.Params.get(), + r.Header, + ) +} + +// IndicesAnalyzeResp represents the returned struct of the index create response +type IndicesAnalyzeResp struct { + Tokens []IndicesAnalyzeToken `json:"tokens"` + Detail struct { + CustomAnalyzer bool `json:"custom_analyzer"` + Charfilters []IndicesAnalyzeCharfilter `json:"charfilters"` + Tokenizer IndicesAnalyzeTokenizer `json:"tokenizer"` + Tokenfilters []IndicesAnalyzeTokenfilters `json:"tokenfilters"` + Analyzer IndicesAnalyzeInfo `json:"analyzer"` + } `json:"detail"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesAnalyzeResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// IndicesAnalyzeToken is a sut type of IndicesAnalyzeResp containing information about analyzer token +type IndicesAnalyzeToken struct { + Token string `json:"token"` + StartOffset int `json:"start_offset"` + EndOffset int `json:"end_offset"` + Type string `json:"type"` + Position int `json:"position"` +} + +// IndicesAnalyzeTokenizer is a sub type of IndicesAnalyzerResp containing information about the tokenizer name and tokens +type IndicesAnalyzeTokenizer struct { + Name string `json:"name"` + Tokens []IndicesAnalyzeToken `json:"tokens"` +} + +// IndicesAnalyzeTokenfilters is a sub type of IndicesAnalyzerResp containing information about the token filers name and tokens +type IndicesAnalyzeTokenfilters struct { + Name string `json:"name"` + Tokens []struct { + Token string `json:"token"` + StartOffset int `json:"start_offset"` + EndOffset int `json:"end_offset"` + Type string `json:"type"` + Position int `json:"position"` + Keyword bool `json:"keyword"` + } `json:"tokens"` +} + +// IndicesAnalyzeCharfilter is a sub type of IndicesAnalyzerResp containing information about the char filter name and filtered text +type IndicesAnalyzeCharfilter struct { + Name string `json:"name"` + FilteredText []string `json:"filtered_text"` +} + +// IndicesAnalyzeInfo is a sub type of IndicesAnalyzerResp containing information about the analyzer name and tokens +type IndicesAnalyzeInfo struct { + Name string `json:"name"` + Tokens []struct { + Token string `json:"token"` + StartOffset int `json:"start_offset"` + EndOffset int `json:"end_offset"` + Type string `json:"type"` + Position int `json:"position"` + Bytes string `json:"bytes"` + PositionLength int `json:"positionLength"` + TermFrequency int `json:"termFrequency"` + } `json:"tokens"` +} diff --git a/opensearchapi/api_indices-block-params.go b/opensearchapi/api_indices-block-params.go new file mode 100644 index 000000000..c1577e887 --- /dev/null +++ b/opensearchapi/api_indices-block-params.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndicesBlockParams represents possible parameters for the IndicesBlockReq +type IndicesBlockParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesBlockParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-block.go b/opensearchapi/api_indices-block.go new file mode 100644 index 000000000..f28781005 --- /dev/null +++ b/opensearchapi/api_indices-block.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesBlockReq represents possible options for the index create request +type IndicesBlockReq struct { + Indices []string + Block string + + Header http.Header + Params IndicesBlockParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesBlockReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(r.Block)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_block/") + path.WriteString(r.Block) + return opensearch.BuildRequest( + "PUT", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesBlockResp represents the returned struct of the index create response +type IndicesBlockResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Indices []struct { + Name string `json:"name"` + Blocked bool `json:"blocked"` + } `json:"indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesBlockResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-cache-params.go b/opensearchapi/api_indices-cache-params.go new file mode 100644 index 000000000..5a9821148 --- /dev/null +++ b/opensearchapi/api_indices-cache-params.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesClearCacheParams represents possible parameters for the IndicesClearCacheReq +type IndicesClearCacheParams struct { + AllowNoIndices *bool + ExpandWildcards string + Fielddata *bool + Fields []string + IgnoreUnavailable *bool + Query *bool + Request *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesClearCacheParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Fielddata != nil { + params["fielddata"] = strconv.FormatBool(*r.Fielddata) + } + + if len(r.Fields) > 0 { + params["fields"] = strings.Join(r.Fields, ",") + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Query != nil { + params["query"] = strconv.FormatBool(*r.Query) + } + + if r.Request != nil { + params["request"] = strconv.FormatBool(*r.Request) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-cache.go b/opensearchapi/api_indices-cache.go new file mode 100644 index 000000000..c0d2d29b2 --- /dev/null +++ b/opensearchapi/api_indices-cache.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesClearCacheReq represents possible options for the index clear cache request +type IndicesClearCacheReq struct { + Indices []string + + Header http.Header + Params IndicesClearCacheParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesClearCacheReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(len("//_cache/clear") + len(indices)) + if len(indices) != 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_cache/clear") + + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesClearCacheResp represents the returned struct of the index clear cache response +type IndicesClearCacheResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesClearCacheResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-clone-params.go b/opensearchapi/api_indices-clone-params.go new file mode 100644 index 000000000..414ca22c0 --- /dev/null +++ b/opensearchapi/api_indices-clone-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// IndicesCloneParams represents possible parameters for the IndicesCloneReq +type IndicesCloneParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesCloneParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-clone.go b/opensearchapi/api_indices-clone.go new file mode 100644 index 000000000..0867f3ae4 --- /dev/null +++ b/opensearchapi/api_indices-clone.go @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesCloneReq represents possible options for the index clone request +type IndicesCloneReq struct { + Index string + Target string + + Body io.Reader + + Header http.Header + Params IndicesCloneParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesCloneReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_clone/%s", r.Index, r.Target), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesCloneResp represents the returned struct of the index clone response +type IndicesCloneResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Index string `json:"index"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesCloneResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-close-params.go b/opensearchapi/api_indices-close-params.go new file mode 100644 index 000000000..2eb19e7d6 --- /dev/null +++ b/opensearchapi/api_indices-close-params.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndicesCloseParams represents possible parameters for the IndicesCloseReq +type IndicesCloseParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesCloseParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-close.go b/opensearchapi/api_indices-close.go new file mode 100644 index 000000000..bb2d0d701 --- /dev/null +++ b/opensearchapi/api_indices-close.go @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesCloseReq represents possible options for the index close request +type IndicesCloseReq struct { + Index string + + Header http.Header + Params IndicesCloseParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesCloseReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_close", r.Index), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesCloseResp represents the returned struct of the index close response +type IndicesCloseResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Indices map[string]struct { + Closed bool `json:"closed"` + } `json:"indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesCloseResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-count-params.go b/opensearchapi/api_indices-count-params.go new file mode 100644 index 000000000..204c16eeb --- /dev/null +++ b/opensearchapi/api_indices-count-params.go @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesCountParams represents possible parameters for the IndicesCountReq +type IndicesCountParams struct { + AllowNoIndices *bool + Analyzer string + AnalyzeWildcard *bool + DefaultOperator string + Df string + ExpandWildcards string + IgnoreThrottled *bool + IgnoreUnavailable *bool + Lenient *bool + MinScore *int + Preference string + Query string + Routing []string + TerminateAfter *int + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesCountParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreThrottled != nil { + params["ignore_throttled"] = strconv.FormatBool(*r.IgnoreThrottled) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.MinScore != nil { + params["min_score"] = strconv.FormatInt(int64(*r.MinScore), 10) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Query != "" { + params["q"] = r.Query + } + + if len(r.Routing) > 0 { + params["routing"] = strings.Join(r.Routing, ",") + } + + if r.TerminateAfter != nil { + params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-count.go b/opensearchapi/api_indices-count.go new file mode 100644 index 000000000..dae30489c --- /dev/null +++ b/opensearchapi/api_indices-count.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesCountReq represents possible options for the index shrink request +type IndicesCountReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params IndicesCountParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesCountReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(8 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_count") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesCountResp represents the returned struct of the index shrink response +type IndicesCountResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Skipped int `json:"skipped"` + Failed int `json:"failed"` + } `json:"_shards"` + Count int `json:"count"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesCountResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-create-params.go b/opensearchapi/api_indices-create-params.go new file mode 100644 index 000000000..c21781a5d --- /dev/null +++ b/opensearchapi/api_indices-create-params.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// IndicesCreateParams represents possible parameters for the IndicesCreateReq +type IndicesCreateParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesCreateParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-create.go b/opensearchapi/api_indices-create.go new file mode 100644 index 000000000..e1353c337 --- /dev/null +++ b/opensearchapi/api_indices-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesCreateReq represents possible options for the index create request +type IndicesCreateReq struct { + Index string + Body io.Reader + Header http.Header + Params IndicesCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("%s%s", "/", r.Index), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesCreateResp represents the returned struct of the index create response +type IndicesCreateResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Index string `json:"index"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-delete-params.go b/opensearchapi/api_indices-delete-params.go new file mode 100644 index 000000000..d862ba791 --- /dev/null +++ b/opensearchapi/api_indices-delete-params.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndicesDeleteParams represents possible parameters for the IndicesDeleteReq +type IndicesDeleteParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesDeleteParams) get() map[string]string { + params := make(map[string]string) + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-delete.go b/opensearchapi/api_indices-delete.go new file mode 100644 index 000000000..6e14200a1 --- /dev/null +++ b/opensearchapi/api_indices-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesDeleteReq represents possible options for the delete indices request +type IndicesDeleteReq struct { + Indices []string + Header http.Header + Params IndicesDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("%s%s", "/", strings.Join(r.Indices, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesDeleteResp represents the returned struct of the delete indices response +type IndicesDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-exists-params.go b/opensearchapi/api_indices-exists-params.go new file mode 100644 index 000000000..9a56e5017 --- /dev/null +++ b/opensearchapi/api_indices-exists-params.go @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strconv" + +// IndicesExistsParams represents possible parameters for the IndicesExistsReq +type IndicesExistsParams struct { + AllowNoIndices *bool + ExpandWildcards string + FlatSettings *bool + IgnoreUnavailable *bool + IncludeDefaults *bool + Local *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.IncludeDefaults != nil { + params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-exists.go b/opensearchapi/api_indices-exists.go new file mode 100644 index 000000000..9f7e0c97a --- /dev/null +++ b/opensearchapi/api_indices-exists.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesExistsReq represents possible options for the index exists request +type IndicesExistsReq struct { + Indices []string + Header http.Header + Params IndicesExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesExistsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("%s%s", "/", strings.Join(r.Indices, ",")), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/opensearchapi/api_indices-field_caps-params.go b/opensearchapi/api_indices-field_caps-params.go new file mode 100644 index 000000000..cb0d5e26b --- /dev/null +++ b/opensearchapi/api_indices-field_caps-params.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesFieldCapsParams represents possible parameters for the IndicesFieldCapsReq +type IndicesFieldCapsParams struct { + AllowNoIndices *bool + ExpandWildcards string + Fields []string + IgnoreUnavailable *bool + IncludeUnmapped *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesFieldCapsParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if len(r.Fields) > 0 { + params["fields"] = strings.Join(r.Fields, ",") + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.IncludeUnmapped != nil { + params["include_unmapped"] = strconv.FormatBool(*r.IncludeUnmapped) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-field_caps.go b/opensearchapi/api_indices-field_caps.go new file mode 100644 index 000000000..527cbb004 --- /dev/null +++ b/opensearchapi/api_indices-field_caps.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesFieldCapsReq represents possible options for the index shrink request +type IndicesFieldCapsReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params IndicesFieldCapsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesFieldCapsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(10 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_field_caps") + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesFieldCapsResp represents the returned struct of the index shrink response +type IndicesFieldCapsResp struct { + Indices []string `json:"indices"` + Fields map[string]map[string]struct { + Type string `json:"type"` + Searchable bool `json:"searchable"` + Aggregatable bool `json:"aggregatable"` + Indices []string `json:"indices"` + } `json:"fields"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesFieldCapsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-flush-params.go b/opensearchapi/api_indices-flush-params.go new file mode 100644 index 000000000..7e70370d2 --- /dev/null +++ b/opensearchapi/api_indices-flush-params.go @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" +) + +// IndicesFlushParams represents possible parameters for the IndicesFlushReq +type IndicesFlushParams struct { + AllowNoIndices *bool + ExpandWildcards string + Force *bool + IgnoreUnavailable *bool + WaitIfOngoing *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesFlushParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Force != nil { + params["force"] = strconv.FormatBool(*r.Force) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.WaitIfOngoing != nil { + params["wait_if_ongoing"] = strconv.FormatBool(*r.WaitIfOngoing) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-flush.go b/opensearchapi/api_indices-flush.go new file mode 100644 index 000000000..cd41ab3cc --- /dev/null +++ b/opensearchapi/api_indices-flush.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesFlushReq represents possible options for the flush indices request +type IndicesFlushReq struct { + Indices []string + + Header http.Header + Params IndicesFlushParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesFlushReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(len("//_flush") + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_flush") + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesFlushResp represents the returned struct of the flush indices response +type IndicesFlushResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesFlushResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-forcemerge-params.go b/opensearchapi/api_indices-forcemerge-params.go new file mode 100644 index 000000000..4602fed6b --- /dev/null +++ b/opensearchapi/api_indices-forcemerge-params.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" +) + +// IndicesForcemergeParams represents possible parameters for the IndicesForcemergeReq +type IndicesForcemergeParams struct { + AllowNoIndices *bool + ExpandWildcards string + Flush *bool + IgnoreUnavailable *bool + MaxNumSegments *int + OnlyExpungeDeletes *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesForcemergeParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Flush != nil { + params["flush"] = strconv.FormatBool(*r.Flush) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MaxNumSegments != nil { + params["max_num_segments"] = strconv.FormatInt(int64(*r.MaxNumSegments), 10) + } + + if r.OnlyExpungeDeletes != nil { + params["only_expunge_deletes"] = strconv.FormatBool(*r.OnlyExpungeDeletes) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-forcemerge.go b/opensearchapi/api_indices-forcemerge.go new file mode 100644 index 000000000..0b435e7e1 --- /dev/null +++ b/opensearchapi/api_indices-forcemerge.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesForcemergeReq represents possible options for the /_forcemerge request +type IndicesForcemergeReq struct { + Indices []string + + Header http.Header + Params IndicesForcemergeParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesForcemergeReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(len("//_forcemerge") + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_forcemerge") + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesForcemergeResp represents the returned struct of the flush indices response +type IndicesForcemergeResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesForcemergeResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-get-params.go b/opensearchapi/api_indices-get-params.go new file mode 100644 index 000000000..0046c6a33 --- /dev/null +++ b/opensearchapi/api_indices-get-params.go @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndicesGetParams represents possible parameters for the IndicesGetReq +type IndicesGetParams struct { + AllowNoIndices *bool + ExpandWildcards string + FlatSettings *bool + IgnoreUnavailable *bool + IncludeDefaults *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesGetParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.IncludeDefaults != nil { + params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-get.go b/opensearchapi/api_indices-get.go new file mode 100644 index 000000000..362df811f --- /dev/null +++ b/opensearchapi/api_indices-get.go @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesGetReq represents possible options for the get indices request +type IndicesGetReq struct { + Indices []string + + Header http.Header + Params IndicesGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/%s", strings.Join(r.Indices, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesGetResp represents the returned struct of the get indices response +type IndicesGetResp struct { + Indices map[string]struct { + Aliases map[string]struct{} `json:"aliases"` + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-mapping-params.go b/opensearchapi/api_indices-mapping-params.go new file mode 100644 index 000000000..87467dc6a --- /dev/null +++ b/opensearchapi/api_indices-mapping-params.go @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// MappingGetParams represents possible parameters for the MappingGetReq +type MappingGetParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r MappingGetParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} + +// MappingPutParams represents possible parameters for the MappingPutReq +type MappingPutParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WriteIndexOnly *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r MappingPutParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WriteIndexOnly != nil { + params["write_index_only"] = strconv.FormatBool(*r.WriteIndexOnly) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-mapping.go b/opensearchapi/api_indices-mapping.go new file mode 100644 index 000000000..7f6ec0a0d --- /dev/null +++ b/opensearchapi/api_indices-mapping.go @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +type mappingClient struct { + apiClient *Client +} + +// Get executes a get mapping request with the required MappingGetReq +func (c mappingClient) Get(ctx context.Context, req *MappingGetReq) (*MappingGetResp, error) { + if req == nil { + req = &MappingGetReq{} + } + + var ( + data MappingGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Put executes a put mapping request with the required MappingPutReq +func (c mappingClient) Put(ctx context.Context, req MappingPutReq) (*MappingPutResp, error) { + var ( + data MappingPutResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Field executes a field mapping request with the optional MappingFieldReq +func (c mappingClient) Field(ctx context.Context, req *MappingFieldReq) (*MappingFieldResp, error) { + if req == nil { + req = &MappingFieldReq{} + } + + var ( + data MappingFieldResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// MappingGetReq represents possible options for the mapping get request +type MappingGetReq struct { + Indices []string + + Header http.Header + Params MappingGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MappingGetReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(10 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_mapping") + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// MappingGetResp represents the returned struct of the mapping get response +type MappingGetResp struct { + Indices map[string]struct { + Mappings json.RawMessage `json:"mappings"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MappingGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// MappingPutReq represents possible options for the mapping put request +type MappingPutReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params MappingPutParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MappingPutReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(10 + len(indices)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_mapping") + return opensearch.BuildRequest( + "PUT", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// MappingPutResp represents the returned struct of the mapping put response +type MappingPutResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MappingPutResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// MappingFieldReq represents possible options for the mapping field request +type MappingFieldReq struct { + Indices []string + Fields []string + + Header http.Header + Params MappingPutParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MappingFieldReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + fields := strings.Join(r.Fields, ",") + + var path strings.Builder + path.Grow(17 + len(indices) + len(fields)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_mapping/field/") + path.WriteString(fields) + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// MappingFieldResp represents the returned struct of the mapping field response +type MappingFieldResp struct { + Indices map[string]struct { + Mappings json.RawMessage `json:"mappings"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MappingFieldResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-open-params.go b/opensearchapi/api_indices-open-params.go new file mode 100644 index 000000000..4f5105755 --- /dev/null +++ b/opensearchapi/api_indices-open-params.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndicesOpenParams represents possible parameters for the IndicesOpenReq +type IndicesOpenParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesOpenParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-open.go b/opensearchapi/api_indices-open.go new file mode 100644 index 000000000..81d448707 --- /dev/null +++ b/opensearchapi/api_indices-open.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesOpenReq represents possible options for the index open request +type IndicesOpenReq struct { + Index string + + Header http.Header + Params IndicesOpenParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesOpenReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_open", r.Index), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesOpenResp represents the returned struct of the index open response +type IndicesOpenResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesOpenResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/internal/build/utils/terminal.go b/opensearchapi/api_indices-recovery-params.go similarity index 62% rename from internal/build/utils/terminal.go rename to opensearchapi/api_indices-recovery-params.go index 731e7603a..d7e4b7f78 100644 --- a/internal/build/utils/terminal.go +++ b/opensearchapi/api_indices-recovery-params.go @@ -24,50 +24,44 @@ // specific language governing permissions and limitations // under the License. -package utils +package opensearchapi import ( - "fmt" - "os" - - "golang.org/x/crypto/ssh/terminal" + "strconv" ) -var ( - isTTY bool - tWidth int -) +// IndicesRecoveryParams represents possible parameters for the IndicesShrinkReq +type IndicesRecoveryParams struct { + ActiveOnly *bool + Detailed *bool -func init() { - isTTY = terminal.IsTerminal(int(os.Stderr.Fd())) - tWidth, _, _ = terminal.GetSize(int(os.Stdout.Fd())) + Pretty bool + Human bool + ErrorTrace bool } -// PrintErr prints an error to STDERR. -// -func PrintErr(err error) { - if isTTY { - fmt.Fprint(os.Stderr, "\x1b[1;37;41m") +func (r IndicesRecoveryParams) get() map[string]string { + params := make(map[string]string) + + if r.ActiveOnly != nil { + params["active_only"] = strconv.FormatBool(*r.ActiveOnly) } - fmt.Fprintf(os.Stderr, "ERROR: %s", err) - if isTTY { - fmt.Fprint(os.Stderr, "\x1b[0m") + + if r.Detailed != nil { + params["detailed"] = strconv.FormatBool(*r.Detailed) } - fmt.Fprint(os.Stderr, "\n") -} -// IsTTY returns true when os.Stderr is a terminal. -// -func IsTTY() bool { - return isTTY -} + if r.Pretty { + params["pretty"] = "true" + } -// TerminalWidth returns the width of terminal, or zero. -// -func TerminalWidth() int { - if tWidth < 0 { - return 0 + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" } - return tWidth + return params } diff --git a/opensearchapi/api_indices-recovery.go b/opensearchapi/api_indices-recovery.go new file mode 100644 index 000000000..c2029be02 --- /dev/null +++ b/opensearchapi/api_indices-recovery.go @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesRecoveryReq represents possible options for the index shrink request +type IndicesRecoveryReq struct { + Indices []string + + Header http.Header + Params IndicesRecoveryParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesRecoveryReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(11 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_recovery") + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesRecoveryResp represents the returned struct of the index shrink response +type IndicesRecoveryResp struct { + Indices map[string]struct { + Shards []struct { + ID int `json:"id"` + Type string `json:"type"` + Stage string `json:"stage"` + Primary bool `json:"primary"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + StopTimeInMillis int64 `json:"stop_time_in_millis"` + TotalTimeInMillis int `json:"total_time_in_millis"` + Source IndicesRecoveryNodeInfo `json:"source"` + Target IndicesRecoveryNodeInfo `json:"target"` + Index struct { + Size struct { + TotalInBytes int `json:"total_in_bytes"` + ReusedInBytes int `json:"reused_in_bytes"` + RecoveredInBytes int `json:"recovered_in_bytes"` + Percent string `json:"percent"` + } `json:"size"` + Files struct { + Total int `json:"total"` + Reused int `json:"reused"` + Recovered int `json:"recovered"` + Percent string `json:"percent"` + } `json:"files"` + TotalTimeInMillis int `json:"total_time_in_millis"` + SourceThrottleTimeInMillis int `json:"source_throttle_time_in_millis"` + TargetThrottleTimeInMillis int `json:"target_throttle_time_in_millis"` + } `json:"index"` + Translog struct { + Recovered int `json:"recovered"` + Total int `json:"total"` + Percent string `json:"percent"` + TotalOnStart int `json:"total_on_start"` + TotalTimeInMillis int `json:"total_time_in_millis"` + } `json:"translog"` + VerifyIndex struct { + CheckIndexTimeInMillis int `json:"check_index_time_in_millis"` + TotalTimeInMillis int `json:"total_time_in_millis"` + } `json:"verify_index"` + } `json:"shards"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesRecoveryResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// IndicesRecoveryNodeInfo is a sub type of IndicesRecoveryResp represeing Node information +type IndicesRecoveryNodeInfo struct { + ID string `json:"id"` + Host string `json:"host"` + TransportAddress string `json:"transport_address"` + IP string `json:"ip"` + Name string `json:"name"` +} diff --git a/opensearchapi/opensearchapi.response_example_test.go b/opensearchapi/api_indices-refresh-params.go similarity index 57% rename from opensearchapi/opensearchapi.response_example_test.go rename to opensearchapi/api_indices-refresh-params.go index d74f6e516..7cc9604f5 100644 --- a/opensearchapi/opensearchapi.response_example_test.go +++ b/opensearchapi/api_indices-refresh-params.go @@ -24,55 +24,49 @@ // specific language governing permissions and limitations // under the License. -package opensearchapi_test +package opensearchapi import ( - "log" - - "github.com/opensearch-project/opensearch-go/v2" + "strconv" ) -func ExampleResponse_IsError() { - client, _ := opensearch.NewDefaultClient() +// IndicesRefreshParams represents possible parameters for the IndicesRefreshReq +type IndicesRefreshParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool - res, err := client.Info() + Pretty bool + Human bool + ErrorTrace bool +} - // Handle connection errors - // - if err != nil { - log.Fatalf("ERROR: %v", err) - } - defer res.Body.Close() +func (r IndicesRefreshParams) get() map[string]string { + params := make(map[string]string) - // Handle error response (4xx, 5xx) - // - if res.IsError() { - log.Fatalf("ERROR: %s", res.Status()) + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) } - // Handle successful response (2xx) - // - log.Println(res) -} - -func ExampleResponse_Status() { - client, _ := opensearch.NewDefaultClient() + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } - res, _ := client.Info() - log.Println(res.Status()) + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } - // 200 OK -} + if r.Pretty { + params["pretty"] = "true" + } -func ExampleResponse_String() { - client, _ := opensearch.NewDefaultClient() + if r.Human { + params["human"] = "true" + } - res, _ := client.Info() - log.Println(res.String()) + if r.ErrorTrace { + params["error_trace"] = "true" + } - // [200 OK] { - // "name" : "opensearch1", - // "cluster_name" : "opensearch-go", - // ... - // } + return params } diff --git a/opensearchapi/api_indices-refresh.go b/opensearchapi/api_indices-refresh.go new file mode 100644 index 000000000..f89999ad9 --- /dev/null +++ b/opensearchapi/api_indices-refresh.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesRefreshReq represents possible options for the /_refresh request +type IndicesRefreshReq struct { + Indices []string + + Header http.Header + Params IndicesRefreshParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesRefreshReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(len("//_refresh") + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_refresh") + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesRefreshResp represents the returned struct of the index shrink response +type IndicesRefreshResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesRefreshResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-resolve-params.go b/opensearchapi/api_indices-resolve-params.go new file mode 100644 index 000000000..2b19b2b25 --- /dev/null +++ b/opensearchapi/api_indices-resolve-params.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +// IndicesResolveParams represents possible parameters for the IndicesResolveReq +type IndicesResolveParams struct { + ExpandWildcards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesResolveParams) get() map[string]string { + params := make(map[string]string) + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-resolve.go b/opensearchapi/api_indices-resolve.go new file mode 100644 index 000000000..6aebd2408 --- /dev/null +++ b/opensearchapi/api_indices-resolve.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesResolveReq represents possible options for the get indices request +type IndicesResolveReq struct { + Indices []string + + Header http.Header + Params IndicesResolveParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesResolveReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_resolve/index/%s", strings.Join(r.Indices, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesResolveResp represents the returned struct of the get indices response +type IndicesResolveResp struct { + Indices []struct { + Name string `json:"name"` + Attributes []string `json:"attributes"` + Aliases []string `json:"aliases"` + } `json:"indices"` + Aliases []struct { + Name string `json:"name"` + Indices []string `json:"indices"` + } `json:"aliases"` + DataStreams []struct { + Name string `json:"name"` + BackingIndices []string `json:"backing_indices"` + TimestampField string `json:"timestamp_field"` + } `json:"data_streams"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesResolveResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/opensearchapi_internal_test.go b/opensearchapi/api_indices-rollover-params.go similarity index 51% rename from opensearchapi/opensearchapi_internal_test.go rename to opensearchapi/api_indices-rollover-params.go index 465c3094e..a3fef775b 100644 --- a/opensearchapi/opensearchapi_internal_test.go +++ b/opensearchapi/api_indices-rollover-params.go @@ -24,56 +24,60 @@ // specific language governing permissions and limitations // under the License. -// +build !integration - package opensearchapi import ( - "testing" + "strconv" "time" ) -func TestAPIHelpers(t *testing.T) { - t.Run("BoolPtr", func(t *testing.T) { - v := BoolPtr(false) - if v == nil || *v != false { - t.Errorf("Expected false, got: %v", v) - } +// IndicesRolloverParams represents possible parameters for the IndicesRolloverReq +type IndicesRolloverParams struct { + DryRun *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesRolloverParams) get() map[string]string { + params := make(map[string]string) + + if r.DryRun != nil { + params["dry_run"] = strconv.FormatBool(*r.DryRun) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } - v = BoolPtr(true) - if v == nil || *v != true { - t.Errorf("Expected true, got: %v", v) - } - }) + if r.Pretty { + params["pretty"] = "true" + } - t.Run("IntPtr", func(t *testing.T) { - v := IntPtr(0) - if v == nil || *v != 0 { - t.Errorf("Expected 0, got: %v", v) - } - }) + if r.Human { + params["human"] = "true" + } - t.Run("FormatDuration", func(t *testing.T) { - var tt = []struct { - duration time.Duration - expected string - }{ - {1 * time.Nanosecond, "1nanos"}, - {100 * time.Nanosecond, "100nanos"}, - {1 * time.Microsecond, "1000nanos"}, - {1 * time.Millisecond, "1ms"}, - {100 * time.Millisecond, "100ms"}, - {1 * time.Minute, "60000ms"}, - {10 * time.Minute, "600000ms"}, - {1 * time.Hour, "3600000ms"}, - {10 * time.Hour, "36000000ms"}, - } + if r.ErrorTrace { + params["error_trace"] = "true" + } - for _, tc := range tt { - actual := formatDuration(tc.duration) - if actual != tc.expected { - t.Errorf("Unexpected output: got=%s, want=%s", actual, tc.expected) - } - } - }) + return params } diff --git a/opensearchapi/api_indices-rollover.go b/opensearchapi/api_indices-rollover.go new file mode 100644 index 000000000..d062f8268 --- /dev/null +++ b/opensearchapi/api_indices-rollover.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesRolloverReq represents possible options for the index shrink request +type IndicesRolloverReq struct { + Alias string + Index string + + Body io.Reader + + Header http.Header + Params IndicesRolloverParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesRolloverReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(12 + len(r.Alias) + len(r.Index)) + path.WriteString("/") + path.WriteString(r.Alias) + path.WriteString("/_rollover") + if len(r.Index) > 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesRolloverResp represents the returned struct of the index shrink response +type IndicesRolloverResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + OldIndex string `json:"old_index"` + NewIndex string `json:"new_index"` + RolledOver bool `json:"rolled_over"` + DryRun bool `json:"dry_run"` + Conditions map[string]bool `json:"conditions"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesRolloverResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-segments-params.go b/opensearchapi/api_indices-segments-params.go new file mode 100644 index 000000000..d726ec524 --- /dev/null +++ b/opensearchapi/api_indices-segments-params.go @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" +) + +// IndicesSegmentsParams represents possible parameters for the IndicesSegmentsReq +type IndicesSegmentsParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Verbose *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesSegmentsParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Verbose != nil { + params["verbose"] = strconv.FormatBool(*r.Verbose) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-segments.go b/opensearchapi/api_indices-segments.go new file mode 100644 index 000000000..9e18ed595 --- /dev/null +++ b/opensearchapi/api_indices-segments.go @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesSegmentsReq represents possible options for the index shrink request +type IndicesSegmentsReq struct { + Indices []string + + Header http.Header + Params IndicesSegmentsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesSegmentsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(11 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_segments") + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesSegmentsResp represents the returned struct of the index shrink response +type IndicesSegmentsResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + Indices map[string]struct { + Shards map[string][]IndicesSegmentsShards `json:"shards"` + } `json:"indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesSegmentsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// IndicesSegmentsShards is a sub type of IndicesSegmentsResp containing information about a shard +type IndicesSegmentsShards struct { + Routing struct { + State string `json:"state"` + Primary bool `json:"primary"` + Node string `json:"node"` + } `json:"routing"` + NumCommittedSegments int `json:"num_committed_segments"` + NumSearchSegments int `json:"num_search_segments"` + Segments map[string]IndicesSegmentsDetails `json:"segments"` +} + +// IndicesSegmentsDetails is a sub type of IndicesSegmentsShards containing information about a segment +type IndicesSegmentsDetails struct { + Generation int `json:"generation"` + NumDocs int `json:"num_docs"` + DeletedDocs int `json:"deleted_docs"` + SizeInBytes int64 `json:"size_in_bytes"` + MemoryInBytes int `json:"memory_in_bytes"` + Committed bool `json:"committed"` + Search bool `json:"search"` + Version string `json:"version"` + Compound bool `json:"compound"` + Sort []struct { + Field string `json:"field"` + Mode string `json:"mode"` + Missing string `json:"missing"` + Reverse bool `json:"reverse"` + } `json:"sort"` + Attributes map[string]string `json:"attributes"` +} diff --git a/opensearchapi/api_indices-settings-params.go b/opensearchapi/api_indices-settings-params.go new file mode 100644 index 000000000..e7537ab81 --- /dev/null +++ b/opensearchapi/api_indices-settings-params.go @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// SettingsGetParams represents possible parameters for the SettingsGetReq +type SettingsGetParams struct { + AllowNoIndices *bool + ExpandWildcards string + FlatSettings *bool + IgnoreUnavailable *bool + IncludeDefaults *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SettingsGetParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.IncludeDefaults != nil { + params["include_defaults"] = strconv.FormatBool(*r.IncludeDefaults) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} + +// SettingsPutParams represents possible parameters for the SettingsPutReq +type SettingsPutParams struct { + AllowNoIndices *bool + ExpandWildcards string + FlatSettings *bool + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + PreserveExisting *bool + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SettingsPutParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.PreserveExisting != nil { + params["preserve_existing"] = strconv.FormatBool(*r.PreserveExisting) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-settings.go b/opensearchapi/api_indices-settings.go new file mode 100644 index 000000000..9188b59bd --- /dev/null +++ b/opensearchapi/api_indices-settings.go @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +type settingsClient struct { + apiClient *Client +} + +// Get executes a get settings request with the required SettingsGetReq +func (c settingsClient) Get(ctx context.Context, req *SettingsGetReq) (*SettingsGetResp, error) { + if req == nil { + req = &SettingsGetReq{} + } + var ( + data SettingsGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Put executes a put settings request with the required SettingsPutReq +func (c settingsClient) Put(ctx context.Context, req SettingsPutReq) (*SettingsPutResp, error) { + var ( + data SettingsPutResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// SettingsGetReq represents possible options for the settings get request +type SettingsGetReq struct { + Indices []string + Settings []string + + Header http.Header + Params SettingsGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SettingsGetReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + settings := strings.Join(r.Settings, ",") + + var path strings.Builder + path.Grow(11 + len(indices) + len(settings)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_settings") + if len(settings) > 0 { + path.WriteString("/") + path.WriteString(settings) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// SettingsGetResp represents the returned struct of the settings get response +type SettingsGetResp struct { + Indices map[string]struct { + Settings json.RawMessage `json:"settings"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SettingsGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// SettingsPutReq represents possible options for the settings put request +type SettingsPutReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params SettingsPutParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SettingsPutReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(10 + len(indices)) + path.WriteString("/") + path.WriteString(indices) + path.WriteString("/_settings") + return opensearch.BuildRequest( + "PUT", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SettingsPutResp represents the returned struct of the settings put response +type SettingsPutResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SettingsPutResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-shardstores-params.go b/opensearchapi/api_indices-shardstores-params.go new file mode 100644 index 000000000..24085c4b6 --- /dev/null +++ b/opensearchapi/api_indices-shardstores-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// IndicesShardStoresParams represents possible parameters for the IndicesShardStoresReq +type IndicesShardStoresParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Status []string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesShardStoresParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if len(r.Status) > 0 { + params["status"] = strings.Join(r.Status, ",") + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-shardstores.go b/opensearchapi/api_indices-shardstores.go new file mode 100644 index 000000000..b09bc6ed2 --- /dev/null +++ b/opensearchapi/api_indices-shardstores.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesShardStoresReq represents possible options for the index shrink request +type IndicesShardStoresReq struct { + Indices []string + + Header http.Header + Params IndicesShardStoresParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesShardStoresReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(15 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_shard_stores") + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesShardStoresResp represents the returned struct of the index shrink response +type IndicesShardStoresResp struct { + Indices map[string]struct { + Shards map[string]struct { + Stores []json.RawMessage `json:"stores"` + } `json:"shards"` + } `json:"indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesShardStoresResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-shrink-params.go b/opensearchapi/api_indices-shrink-params.go new file mode 100644 index 000000000..3d889eb34 --- /dev/null +++ b/opensearchapi/api_indices-shrink-params.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndicesShrinkParams represents possible parameters for the IndicesShrinkReq +type IndicesShrinkParams struct { + CopySettings *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesShrinkParams) get() map[string]string { + params := make(map[string]string) + + if r.CopySettings != nil { + params["copy_settings"] = strconv.FormatBool(*r.CopySettings) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-shrink.go b/opensearchapi/api_indices-shrink.go new file mode 100644 index 000000000..00baf1bd9 --- /dev/null +++ b/opensearchapi/api_indices-shrink.go @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesShrinkReq represents possible options for the index shrink request +type IndicesShrinkReq struct { + Index string + Target string + + Body io.Reader + + Header http.Header + Params IndicesShrinkParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesShrinkReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_shrink/%s", r.Index, r.Target), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesShrinkResp represents the returned struct of the index shrink response +type IndicesShrinkResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Index string `json:"index"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesShrinkResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-split-params.go b/opensearchapi/api_indices-split-params.go new file mode 100644 index 000000000..579d582d4 --- /dev/null +++ b/opensearchapi/api_indices-split-params.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndicesSplitParams represents possible parameters for the IndicesSplitReq +type IndicesSplitParams struct { + CopySettings *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesSplitParams) get() map[string]string { + params := make(map[string]string) + + if r.CopySettings != nil { + params["copy_settings"] = strconv.FormatBool(*r.CopySettings) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-split.go b/opensearchapi/api_indices-split.go new file mode 100644 index 000000000..738d7a2ab --- /dev/null +++ b/opensearchapi/api_indices-split.go @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesSplitReq represents possible options for the index split request +type IndicesSplitReq struct { + Index string + Target string + + Body io.Reader + + Header http.Header + Params IndicesSplitParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesSplitReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_split/%s", r.Index, r.Target), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesSplitResp represents the returned struct of the index split response +type IndicesSplitResp struct { + Acknowledged bool `json:"acknowledged"` + ShardsAcknowledged bool `json:"shards_acknowledged"` + Index string `json:"index"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesSplitResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices-stats-params.go b/opensearchapi/api_indices-stats-params.go new file mode 100644 index 000000000..e48f37ed3 --- /dev/null +++ b/opensearchapi/api_indices-stats-params.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IndicesStatsParams represents possible parameters for the IndicesStatsReq +type IndicesStatsParams struct { + CopySettings *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesStatsParams) get() map[string]string { + params := make(map[string]string) + + if r.CopySettings != nil { + params["copy_settings"] = strconv.FormatBool(*r.CopySettings) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-stats.go b/opensearchapi/api_indices-stats.go new file mode 100644 index 000000000..b29c2611a --- /dev/null +++ b/opensearchapi/api_indices-stats.go @@ -0,0 +1,307 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesStatsReq represents possible options for the index shrink request +type IndicesStatsReq struct { + Indices []string + Metrics []string + + Header http.Header + Params IndicesStatsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesStatsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + metrics := strings.Join(r.Metrics, ",") + + var path strings.Builder + path.Grow(9 + len(indices) + len(metrics)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_stats") + if len(metrics) > 0 { + path.WriteString("/") + path.WriteString(metrics) + } + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// IndicesStatsResp represents the returned struct of the index shrink response +type IndicesStatsResp struct { + Shards IndicesStatsShards `json:"_shards"` + All IndicesStatsAll `json:"_all"` + Indices IndicesStatsIndices `json:"indices"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesStatsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// IndicesStatsShards is a sub type of IndicesStatsResp containing information about how many shards got requested +type IndicesStatsShards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` +} + +// IndicesStatsDocs is a sub type of IndicesStatsInfo containing stats about the index documents +type IndicesStatsDocs struct { + Count int `json:"count"` + Deleted int `json:"deleted"` +} + +// IndicesStatsStore is a sub type of IndicesStatsInfo containing stats about index storage +type IndicesStatsStore struct { + SizeInBytes int64 `json:"size_in_bytes"` + ReservedInBytes int `json:"reserved_in_bytes"` +} + +// IndicesStatsIndexing is a sub type of IndicesStatsInfo containing stats about document indexing +type IndicesStatsIndexing struct { + IndexTotal int `json:"index_total"` + IndexTimeInMillis int `json:"index_time_in_millis"` + IndexCurrent int `json:"index_current"` + IndexFailed int `json:"index_failed"` + DeleteTotal int `json:"delete_total"` + DeleteTimeInMillis int `json:"delete_time_in_millis"` + DeleteCurrent int `json:"delete_current"` + NoopUpdateTotal int `json:"noop_update_total"` + IsThrottled bool `json:"is_throttled"` + ThrottleTimeInMillis int `json:"throttle_time_in_millis"` + DocStatus map[string]int `json:"doc_status"` +} + +// IndicesStatsGet is a sub type of IndicesStatsInfo containing stats about index get +type IndicesStatsGet struct { + Total int `json:"total"` + TimeInMillis int `json:"time_in_millis"` + ExistsTotal int `json:"exists_total"` + ExistsTimeInMillis int `json:"exists_time_in_millis"` + MissingTotal int `json:"missing_total"` + MissingTimeInMillis int `json:"missing_time_in_millis"` + Current int `json:"current"` +} + +// IndicesStatsSearch is a sub type of IndicesStatsInfo containing stats about index search +type IndicesStatsSearch struct { + OpenContexts int `json:"open_contexts"` + QueryTotal int `json:"query_total"` + QueryTimeInMillis int `json:"query_time_in_millis"` + QueryCurrent int `json:"query_current"` + FetchTotal int `json:"fetch_total"` + FetchTimeInMillis int `json:"fetch_time_in_millis"` + FetchCurrent int `json:"fetch_current"` + ScrollTotal int `json:"scroll_total"` + ScrollTimeInMillis int `json:"scroll_time_in_millis"` + ScrollCurrent int `json:"scroll_current"` + PointInTimeTotal int `json:"point_in_time_total"` + PointInTimeTimeInMillis int `json:"point_in_time_time_in_millis"` + PointInTimeCurrent int `json:"point_in_time_current"` + SuggestTotal int `json:"suggest_total"` + SuggestTimeInMillis int `json:"suggest_time_in_millis"` + SuggestCurrent int `json:"suggest_current"` +} + +// IndicesStatsMerges is a sub type of IndicesStatsInfo containing stats about index merges +type IndicesStatsMerges struct { + Current int `json:"current"` + CurrentDocs int `json:"current_docs"` + CurrentSizeInBytes int `json:"current_size_in_bytes"` + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` + TotalDocs int `json:"total_docs"` + TotalSizeInBytes int64 `json:"total_size_in_bytes"` + TotalStoppedTimeInMillis int `json:"total_stopped_time_in_millis"` + TotalThrottledTimeInMillis int `json:"total_throttled_time_in_millis"` + TotalAutoThrottleInBytes int `json:"total_auto_throttle_in_bytes"` + UnreferencedFileCleanupsPerformed int `json:"unreferenced_file_cleanups_performed"` +} + +// IndicesStatsRefresh is a sub type of IndicesStatsInfo containing stats about index refresh +type IndicesStatsRefresh struct { + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` + ExternalTotal int `json:"external_total"` + ExternalTotalTimeInMillis int `json:"external_total_time_in_millis"` + Listeners int `json:"listeners"` +} + +// IndicesStatsFlush is a sub type of IndicesStatsInfo containing stats about index flush +type IndicesStatsFlush struct { + Total int `json:"total"` + Periodic int `json:"periodic"` + TotalTimeInMillis int `json:"total_time_in_millis"` +} + +// IndicesStatsWarmer is a sub type of IndicesStatsInfo containing stats about index warmer +type IndicesStatsWarmer struct { + Current int `json:"current"` + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` +} + +// IndicesStatsQueryCache is a sub type of IndicesStatsInfo containing stats about index query cache +type IndicesStatsQueryCache struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + TotalCount int `json:"total_count"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` + CacheSize int `json:"cache_size"` + CacheCount int `json:"cache_count"` + Evictions int `json:"evictions"` +} + +// IndicesStatsFielddata is a sub type of IndicesStatsInfo containing stats about index fielddata +type IndicesStatsFielddata struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + Evictions int `json:"evictions"` +} + +// IndicesStatsCompletion is a sub type of IndicesStatsInfo containing stats about index completion +type IndicesStatsCompletion struct { + SizeInBytes int `json:"size_in_bytes"` +} + +// IndicesStatsSegments is a sub type of IndicesStatsInfo containing stats about index segments +type IndicesStatsSegments struct { + Count int `json:"count"` + MemoryInBytes int `json:"memory_in_bytes"` + TermsMemoryInBytes int `json:"terms_memory_in_bytes"` + StoredFieldsMemoryInBytes int `json:"stored_fields_memory_in_bytes"` + TermVectorsMemoryInBytes int `json:"term_vectors_memory_in_bytes"` + NormsMemoryInBytes int `json:"norms_memory_in_bytes"` + PointsMemoryInBytes int `json:"points_memory_in_bytes"` + DocValuesMemoryInBytes int `json:"doc_values_memory_in_bytes"` + IndexWriterMemoryInBytes int `json:"index_writer_memory_in_bytes"` + VersionMapMemoryInBytes int `json:"version_map_memory_in_bytes"` + FixedBitSetMemoryInBytes int `json:"fixed_bit_set_memory_in_bytes"` + MaxUnsafeAutoIDTimestamp int64 `json:"max_unsafe_auto_id_timestamp"` + RemoteStore struct { + Upload struct { + TotalUploadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_upload_size"` + RefreshSizeLag struct { + TotalBytes int `json:"total_bytes"` + MaxBytes int `json:"max_bytes"` + } `json:"refresh_size_lag"` + MaxRefreshTimeLagInMillis int `json:"max_refresh_time_lag_in_millis"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + } `json:"upload"` + Download struct { + TotalDownloadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_download_size"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + } `json:"download"` + } `json:"remote_store"` + SegmentReplication struct { + // Type is json.RawMessage due to difference in opensearch versions from string to int + MaxBytesBehind json.RawMessage `json:"max_bytes_behind"` + TotalBytesBehind json.RawMessage `json:"total_bytes_behind"` + MaxReplicationLag json.RawMessage `json:"max_replication_lag"` + } `json:"segment_replication"` + FileSizes json.RawMessage `json:"file_sizes"` +} + +// IndicesStatsTranslog is a sub type of IndicesStatsInfo containing stats about index translog +type IndicesStatsTranslog struct { + Operations int `json:"operations"` + SizeInBytes int `json:"size_in_bytes"` + UncommittedOperations int `json:"uncommitted_operations"` + UncommittedSizeInBytes int `json:"uncommitted_size_in_bytes"` + EarliestLastModifiedAge int `json:"earliest_last_modified_age"` + RemoteStore struct { + Upload struct { + TotalUploads struct { + Started int `json:"started"` + Failed int `json:"failed"` + Succeeded int `json:"succeeded"` + } `json:"total_uploads"` + TotalUploadSize struct { + StartedBytes int `json:"started_bytes"` + FailedBytes int `json:"failed_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + } `json:"total_upload_size"` + } `json:"upload"` + } `json:"remote_store"` +} + +// IndicesStatsRequestCache is a sub type of IndicesStatsInfo containing stats about index request cache +type IndicesStatsRequestCache struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + Evictions int `json:"evictions"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` +} + +// IndicesStatsRecovery is a sub type of IndicesStatsInfo containing stats about index recovery +type IndicesStatsRecovery struct { + CurrentAsSource int `json:"current_as_source"` + CurrentAsTarget int `json:"current_as_target"` + ThrottleTimeInMillis int `json:"throttle_time_in_millis"` +} + +// IndicesStatsInfo is a sub type of IndicesStatsAll, IndicesStatsDetails aggregating all document stats +type IndicesStatsInfo struct { + Docs IndicesStatsDocs `json:"docs"` + Store IndicesStatsStore `json:"store"` + Indexing IndicesStatsIndexing `json:"indexing"` + Get IndicesStatsGet `json:"get"` + Search IndicesStatsSearch `json:"search"` + Merges IndicesStatsMerges `json:"merges"` + Refresh IndicesStatsRefresh `json:"refresh"` + Flush IndicesStatsFlush `json:"flush"` + Warmer IndicesStatsWarmer `json:"warmer"` + QueryCache IndicesStatsQueryCache `json:"query_cache"` + Fielddata IndicesStatsFielddata `json:"fielddata"` + Completion IndicesStatsCompletion `json:"completion"` + Segments IndicesStatsSegments `json:"segments"` + Translog IndicesStatsTranslog `json:"translog"` + RequestCache IndicesStatsRequestCache `json:"request_cache"` + Recovery IndicesStatsRecovery `json:"recovery"` +} + +// IndicesStatsAll is a sub type of IndicesStatsResp containing information about docs stats from all indices +type IndicesStatsAll struct { + Primaries IndicesStatsInfo `json:"primaries"` + Total IndicesStatsInfo `json:"total"` +} + +// IndicesStatsDetails is a sub type of IndicesStatsIndices containing the information about the index uuid and index stats +type IndicesStatsDetails struct { + UUID string `json:"uuid"` + Primaries IndicesStatsInfo `json:"primaries"` + Total IndicesStatsInfo `json:"total"` +} + +// IndicesStatsIndices is a sub type of IndicesStatsResp containing information about docs stats from specific indices +type IndicesStatsIndices map[string]IndicesStatsDetails diff --git a/opensearchapi/api_indices-validate-params.go b/opensearchapi/api_indices-validate-params.go new file mode 100644 index 000000000..45115867a --- /dev/null +++ b/opensearchapi/api_indices-validate-params.go @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" +) + +// IndicesValidateQueryParams represents possible parameters for the IndicesValidateQueryReq +type IndicesValidateQueryParams struct { + AllowNoIndices *bool + AllShards *bool + Analyzer string + AnalyzeWildcard *bool + DefaultOperator string + Df string + ExpandWildcards string + Explain *bool + IgnoreUnavailable *bool + Lenient *bool + Query string + Rewrite *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IndicesValidateQueryParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.AllShards != nil { + params["all_shards"] = strconv.FormatBool(*r.AllShards) + } + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Explain != nil { + params["explain"] = strconv.FormatBool(*r.Explain) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.Query != "" { + params["q"] = r.Query + } + + if r.Rewrite != nil { + params["rewrite"] = strconv.FormatBool(*r.Rewrite) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_indices-validate.go b/opensearchapi/api_indices-validate.go new file mode 100644 index 000000000..99d407a8c --- /dev/null +++ b/opensearchapi/api_indices-validate.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IndicesValidateQueryReq represents possible options for the index shrink request +type IndicesValidateQueryReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params IndicesValidateQueryParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IndicesValidateQueryReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(17 + len(indices)) + if len(indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_validate/query") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IndicesValidateQueryResp represents the returned struct of the index shrink response +type IndicesValidateQueryResp struct { + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + Valid bool `json:"valid"` + Error *string `json:"error"` + Explanations []struct { + Index string `json:"index"` + Shard int `json:"shard"` + Valid bool `json:"valid"` + Explanation *string `json:"explanation"` + Error *string `json:"error"` + } `json:"explanations"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IndicesValidateQueryResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_indices.go b/opensearchapi/api_indices.go new file mode 100644 index 000000000..8abfa6638 --- /dev/null +++ b/opensearchapi/api_indices.go @@ -0,0 +1,360 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v2" +) + +type indicesClient struct { + apiClient *Client + Alias aliasClient + Mapping mappingClient + Settings settingsClient +} + +// Delete executes a delete indices request with the required IndicesDeleteReq +func (c indicesClient) Delete(ctx context.Context, req IndicesDeleteReq) (*IndicesDeleteResp, error) { + var ( + data IndicesDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Create executes a creade indices request with the required IndicesCreateReq +func (c indicesClient) Create(ctx context.Context, req IndicesCreateReq) (*IndicesCreateResp, error) { + var ( + data IndicesCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes a exists indices request with the required IndicesExistsReq +func (c indicesClient) Exists(ctx context.Context, req IndicesExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} + +// Block executes a //_block request with the required IndicesBlockReq +func (c indicesClient) Block(ctx context.Context, req IndicesBlockReq) (*IndicesBlockResp, error) { + var ( + data IndicesBlockResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Analyze executes a //_analyze request with the required IndicesAnalyzeReq +func (c indicesClient) Analyze(ctx context.Context, req IndicesAnalyzeReq) (*IndicesAnalyzeResp, error) { + var ( + data IndicesAnalyzeResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// ClearCache executes a //_cache/clear request with the optional IndicesClearCacheReq +func (c indicesClient) ClearCache(ctx context.Context, req *IndicesClearCacheReq) (*IndicesClearCacheResp, error) { + if req == nil { + req = &IndicesClearCacheReq{} + } + + var ( + data IndicesClearCacheResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Clone executes a //_clone/ request with the required IndicesCloneReq +func (c indicesClient) Clone(ctx context.Context, req IndicesCloneReq) (*IndicesCloneResp, error) { + var ( + data IndicesCloneResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Close executes a //_close request with the required IndicesCloseReq +func (c indicesClient) Close(ctx context.Context, req IndicesCloseReq) (*IndicesCloseResp, error) { + var ( + data IndicesCloseResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a / request with the required IndicesGetReq +func (c indicesClient) Get(ctx context.Context, req IndicesGetReq) (*IndicesGetResp, error) { + var ( + data IndicesGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Indices); err != nil { + return &data, err + } + + return &data, nil +} + +// Open executes a //_open request with the required IndicesOpenReq +func (c indicesClient) Open(ctx context.Context, req IndicesOpenReq) (*IndicesOpenResp, error) { + var ( + data IndicesOpenResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Shrink executes a //_shrink/ request with the required IndicesShrinkReq +func (c indicesClient) Shrink(ctx context.Context, req IndicesShrinkReq) (*IndicesShrinkResp, error) { + var ( + data IndicesShrinkResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Split executes a //_split/ request with the required IndicesSplitReq +func (c indicesClient) Split(ctx context.Context, req IndicesSplitReq) (*IndicesSplitResp, error) { + var ( + data IndicesSplitResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Flush executes a //_flush request with the optional IndicesFlushReq +func (c indicesClient) Flush(ctx context.Context, req *IndicesFlushReq) (*IndicesFlushResp, error) { + if req == nil { + req = &IndicesFlushReq{} + } + + var ( + data IndicesFlushResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Forcemerge executes a //_forcemerge request with the optional IndicesForcemergeReq +func (c indicesClient) Forcemerge(ctx context.Context, req *IndicesForcemergeReq) (*IndicesForcemergeResp, error) { + if req == nil { + req = &IndicesForcemergeReq{} + } + + var ( + data IndicesForcemergeResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Recovery executes a //_recovery request with the optional IndicesRecoveryReq +func (c indicesClient) Recovery(ctx context.Context, req *IndicesRecoveryReq) (*IndicesRecoveryResp, error) { + if req == nil { + req = &IndicesRecoveryReq{} + } + + var ( + data IndicesRecoveryResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Refresh executes a //_refresh request with the optional IndicesRefreshReq +func (c indicesClient) Refresh(ctx context.Context, req *IndicesRefreshReq) (*IndicesRefreshResp, error) { + if req == nil { + req = &IndicesRefreshReq{} + } + + var ( + data IndicesRefreshResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Rollover executes a //_rollover request with the required IndicesRolloverReq +func (c indicesClient) Rollover(ctx context.Context, req IndicesRolloverReq) (*IndicesRolloverResp, error) { + var ( + data IndicesRolloverResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Segments executes a //_segments request with the optional IndicesSegmentsReq +func (c indicesClient) Segments(ctx context.Context, req *IndicesSegmentsReq) (*IndicesSegmentsResp, error) { + if req == nil { + req = &IndicesSegmentsReq{} + } + + var ( + data IndicesSegmentsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// ShardStores executes a //_shard_stores request with the optional IndicesShardStoresReq +func (c indicesClient) ShardStores(ctx context.Context, req *IndicesShardStoresReq) (*IndicesShardStoresResp, error) { + if req == nil { + req = &IndicesShardStoresReq{} + } + + var ( + data IndicesShardStoresResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Stats executes a //_stats request with the optional IndicesStatsReq +func (c indicesClient) Stats(ctx context.Context, req *IndicesStatsReq) (*IndicesStatsResp, error) { + if req == nil { + req = &IndicesStatsReq{} + } + + var ( + data IndicesStatsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// ValidateQuery executes a //_validate/query request with the required IndicesValidateQueryReq +func (c indicesClient) ValidateQuery(ctx context.Context, req IndicesValidateQueryReq) (*IndicesValidateQueryResp, error) { + var ( + data IndicesValidateQueryResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Count executes a //_count request with the required IndicesCountReq +func (c indicesClient) Count(ctx context.Context, req *IndicesCountReq) (*IndicesCountResp, error) { + if req == nil { + req = &IndicesCountReq{} + } + + var ( + data IndicesCountResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// FieldCaps executes a //_field_caps request with the required IndicesFieldCapsReq +func (c indicesClient) FieldCaps(ctx context.Context, req IndicesFieldCapsReq) (*IndicesFieldCapsResp, error) { + var ( + data IndicesFieldCapsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Resolve executes a /_resolve/index/ request with the required IndicesResolveReq +func (c indicesClient) Resolve(ctx context.Context, req IndicesResolveReq) (*IndicesResolveResp, error) { + var ( + data IndicesResolveResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_indices_test.go b/opensearchapi/api_indices_test.go new file mode 100644 index 000000000..a2dc0142c --- /dev/null +++ b/opensearchapi/api_indices_test.go @@ -0,0 +1,924 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +type dummyInspect struct { + response *opensearch.Response +} + +func (r dummyInspect) Inspect() opensearchapi.Inspect { + return opensearchapi.Inspect{Response: r.response} +} + +func TestIndicesClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + index := "test-indices-create" + indexClone := "test-indices-clone" + indexSplit := "test-indices-split" + indexShrink := "test-indices-shrink" + indexRollover := "test-indices-rollover" + alias := "test-indices-alias" + testIndices := []string{index, indexClone, indexSplit, indexShrink, indexRollover} + _, err = client.Indices.Delete( + nil, + opensearchapi.IndicesDeleteReq{ + Indices: testIndices, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + require.Nil(t, err) + + type indicesTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []indicesTests + }{ + { + Name: "Create", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Create(nil, opensearchapi.IndicesCreateReq{Index: index}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Create(nil, opensearchapi.IndicesCreateReq{Index: index}) + }, + }, + }, + }, + { + Name: "Exists", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = client.Indices.Exists(nil, opensearchapi.IndicesExistsReq{Indices: []string{index}}) + return resp, err + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = failingClient.Indices.Exists(nil, opensearchapi.IndicesExistsReq{Indices: []string{index}}) + return resp, err + }, + }, + }, + }, + { + Name: "Block", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Block(nil, opensearchapi.IndicesBlockReq{Indices: []string{index}, Block: "write"}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Block(nil, opensearchapi.IndicesBlockReq{Indices: []string{index}, Block: "write"}) + }, + }, + }, + }, + { + Name: "Analyze", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Analyze(nil, opensearchapi.IndicesAnalyzeReq{Body: opensearchapi.IndicesAnalyzeBody{Text: []string{"test"}, Analyzer: "standard"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Analyze(nil, opensearchapi.IndicesAnalyzeReq{Body: opensearchapi.IndicesAnalyzeBody{Text: []string{"test"}, Analyzer: "standard"}}) + }, + }, + }, + }, + { + Name: "ClearCache", + Tests: []indicesTests{ + { + Name: "without request", + Results: func() (osapitest.Response, error) { + return client.Indices.ClearCache(nil, nil) + }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.ClearCache(nil, &opensearchapi.IndicesClearCacheReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.ClearCache(nil, nil) + }, + }, + }, + }, + { + Name: "Alias Put", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Alias.Put(nil, opensearchapi.AliasPutReq{Indices: []string{index}, Alias: alias}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Alias.Put(nil, opensearchapi.AliasPutReq{Indices: []string{index}, Alias: alias}) + }, + }, + }, + }, + { + Name: "Alias Get", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Alias.Get(nil, opensearchapi.AliasGetReq{Indices: []string{index}, Alias: []string{alias}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Alias.Get(nil, opensearchapi.AliasGetReq{Indices: []string{index}, Alias: []string{alias}}) + }, + }, + }, + }, + { + Name: "Alias Exists", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = client.Indices.Alias.Exists(nil, opensearchapi.AliasExistsReq{Indices: []string{index}, Alias: []string{alias}}) + return resp, err + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = failingClient.Indices.Alias.Exists(nil, opensearchapi.AliasExistsReq{Indices: []string{index}, Alias: []string{alias}}) + return resp, err + }, + }, + }, + }, + { + Name: "Rollover", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Rollover(nil, opensearchapi.IndicesRolloverReq{Alias: alias, Index: indexRollover}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Rollover(nil, opensearchapi.IndicesRolloverReq{Alias: alias, Index: indexRollover}) + }, + }, + }, + }, + { + Name: "Alias Delete", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Alias.Delete(nil, opensearchapi.AliasDeleteReq{Indices: []string{indexRollover}, Alias: []string{alias}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Alias.Delete(nil, opensearchapi.AliasDeleteReq{Indices: []string{indexRollover}, Alias: []string{alias}}) + }, + }, + }, + }, + { + Name: "Mapping Put", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Mapping.Put(nil, opensearchapi.MappingPutReq{Indices: []string{index}, Body: strings.NewReader(`{"properties":{"test":{"type":"text"}}}`)}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Mapping.Put(nil, opensearchapi.MappingPutReq{Indices: []string{index}, Body: strings.NewReader(`{"properties":{"test":{"type":"text"}}}`)}) + }, + }, + }, + }, + { + Name: "Mapping Get", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Mapping.Get(nil, &opensearchapi.MappingGetReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Mapping.Get(nil, &opensearchapi.MappingGetReq{Indices: []string{index}}) + }, + }, + }, + }, + { + Name: "Mapping Field", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Mapping.Field(nil, &opensearchapi.MappingFieldReq{Indices: []string{index}, Fields: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Mapping.Field(nil, &opensearchapi.MappingFieldReq{Indices: []string{index}, Fields: []string{"*"}}) + }, + }, + }, + }, + { + Name: "Settings Put", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Settings.Put(nil, opensearchapi.SettingsPutReq{Indices: []string{index}, Body: strings.NewReader(`{"number_of_replicas":0}`)}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Settings.Put(nil, opensearchapi.SettingsPutReq{Indices: []string{index}, Body: strings.NewReader(`{"number_of_replicas":1}`)}) + }, + }, + }, + }, + { + Name: "Settings Get", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Settings.Get(nil, &opensearchapi.SettingsGetReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Settings.Get(nil, &opensearchapi.SettingsGetReq{Indices: []string{index}}) + }, + }, + }, + }, + { + Name: "Flush", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Flush(nil, &opensearchapi.IndicesFlushReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Flush(nil, &opensearchapi.IndicesFlushReq{Indices: []string{index}}) + }, + }, + }, + }, + { + Name: "Forcemerge", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Forcemerge(nil, &opensearchapi.IndicesForcemergeReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Forcemerge(nil, &opensearchapi.IndicesForcemergeReq{Indices: []string{index}}) + }, + }, + }, + }, + { + Name: "Clone", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Clone(nil, opensearchapi.IndicesCloneReq{Index: index, Target: indexClone}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Clone(nil, opensearchapi.IndicesCloneReq{Index: index, Target: indexClone}) + }, + }, + }, + }, + { + Name: "Split", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Split( + nil, + opensearchapi.IndicesSplitReq{ + Index: index, + Target: indexSplit, + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":2,"number_of_replicas":0}}}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Split(nil, opensearchapi.IndicesSplitReq{Index: index, Target: indexSplit}) + }, + }, + }, + }, + { + Name: "Shrink", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Shrink( + nil, + opensearchapi.IndicesShrinkReq{ + Index: indexSplit, + Target: indexShrink, + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":1,"number_of_replicas":0}}}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Shrink(nil, opensearchapi.IndicesShrinkReq{Index: index, Target: indexClone}) + }, + }, + }, + }, + { + Name: "Get", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Get(nil, opensearchapi.IndicesGetReq{Indices: []string{index, indexClone}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Get(nil, opensearchapi.IndicesGetReq{Indices: []string{index, indexClone}}) + }, + }, + }, + }, + { + Name: "Recovery", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Recovery(nil, &opensearchapi.IndicesRecoveryReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Recovery(nil, &opensearchapi.IndicesRecoveryReq{Indices: []string{index}}) + }, + }, + }, + }, + { + Name: "Refresh", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Refresh(nil, &opensearchapi.IndicesRefreshReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Refresh(nil, &opensearchapi.IndicesRefreshReq{Indices: []string{index}}) + }, + }, + }, + }, + { + Name: "Segments", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Segments(nil, &opensearchapi.IndicesSegmentsReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Segments(nil, &opensearchapi.IndicesSegmentsReq{Indices: []string{index}}) + }, + }, + }, + }, + { + Name: "ShardStores", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.ShardStores(nil, &opensearchapi.IndicesShardStoresReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.ShardStores(nil, &opensearchapi.IndicesShardStoresReq{Indices: []string{index}}) + }, + }, + }, + }, + { + Name: "Stats", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Stats(nil, &opensearchapi.IndicesStatsReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Stats(nil, &opensearchapi.IndicesStatsReq{Indices: []string{index}}) + }, + }, + }, + }, + { + Name: "ValidateQuery", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.ValidateQuery(nil, opensearchapi.IndicesValidateQueryReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.ValidateQuery(nil, opensearchapi.IndicesValidateQueryReq{Indices: []string{index}}) + }, + }, + }, + }, + { + Name: "Count", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Count( + nil, + &opensearchapi.IndicesCountReq{ + Indices: []string{index}, + Body: strings.NewReader(`{"query":{"match":{"test":"TEXT"}}}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Count(nil, nil) + }, + }, + }, + }, + { + Name: "FieldCaps", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.FieldCaps( + nil, + opensearchapi.IndicesFieldCapsReq{ + Indices: []string{index}, + Params: opensearchapi.IndicesFieldCapsParams{Fields: []string{"*"}}, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.FieldCaps( + nil, + opensearchapi.IndicesFieldCapsReq{ + Params: opensearchapi.IndicesFieldCapsParams{Fields: []string{"*"}}, + }, + ) + }, + }, + }, + }, + { + Name: "Resolve", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Resolve(nil, opensearchapi.IndicesResolveReq{Indices: []string{index}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Resolve(nil, opensearchapi.IndicesResolveReq{}) + }, + }, + }, + }, + { + Name: "Close", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Close(nil, opensearchapi.IndicesCloseReq{Index: index}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Close(nil, opensearchapi.IndicesCloseReq{Index: index}) + }, + }, + }, + }, + { + Name: "Open", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Open(nil, opensearchapi.IndicesOpenReq{Index: index}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Open(nil, opensearchapi.IndicesOpenReq{Index: index}) + }, + }, + }, + }, + { + Name: "Delete", + Tests: []indicesTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: testIndices}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: testIndices}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + } + }) + } + }) + } + + t.Run("ValidateResponse", func(t *testing.T) { + _, err = client.Indices.Delete( + nil, + opensearchapi.IndicesDeleteReq{ + Indices: testIndices, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + require.Nil(t, err) + + t.Run("Create", func(t *testing.T) { + resp, err := client.Indices.Create(nil, opensearchapi.IndicesCreateReq{Index: index}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Block", func(t *testing.T) { + resp, err := client.Indices.Block(nil, opensearchapi.IndicesBlockReq{Indices: []string{index}, Block: "write"}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Analyze", func(t *testing.T) { + resp, err := client.Indices.Analyze(nil, opensearchapi.IndicesAnalyzeReq{Body: opensearchapi.IndicesAnalyzeBody{Text: []string{"test"}, Analyzer: "standard", Explain: true}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("ClearCache", func(t *testing.T) { + resp, err := client.Indices.ClearCache(nil, &opensearchapi.IndicesClearCacheReq{Indices: []string{index}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Alias Put", func(t *testing.T) { + resp, err := client.Indices.Alias.Put(nil, opensearchapi.AliasPutReq{Indices: []string{index}, Alias: alias}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Alias Get", func(t *testing.T) { + resp, err := client.Indices.Alias.Get(nil, opensearchapi.AliasGetReq{Indices: []string{index}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Indices, resp.Inspect().Response) + }) + t.Run("Rollover", func(t *testing.T) { + resp, err := client.Indices.Rollover(nil, opensearchapi.IndicesRolloverReq{Alias: alias, Index: indexRollover}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Alias Delete", func(t *testing.T) { + resp, err := client.Indices.Alias.Delete(nil, opensearchapi.AliasDeleteReq{Indices: []string{indexRollover}, Alias: []string{alias}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Mapping Put", func(t *testing.T) { + resp, err := client.Indices.Mapping.Put(nil, opensearchapi.MappingPutReq{Indices: []string{index}, Body: strings.NewReader(`{"properties":{"test":{"type":"text"}}}`)}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Mapping Get", func(t *testing.T) { + resp, err := client.Indices.Mapping.Get(nil, &opensearchapi.MappingGetReq{Indices: []string{index}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Indices, resp.Inspect().Response) + }) + t.Run("Mapping Field", func(t *testing.T) { + resp, err := client.Indices.Mapping.Field(nil, &opensearchapi.MappingFieldReq{Fields: []string{"*"}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Indices, resp.Inspect().Response) + }) + t.Run("Settings Put", func(t *testing.T) { + resp, err := client.Indices.Settings.Put(nil, opensearchapi.SettingsPutReq{Indices: []string{index}, Body: strings.NewReader(`{"number_of_replicas":1}`)}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Settings Get", func(t *testing.T) { + resp, err := client.Indices.Settings.Get(nil, &opensearchapi.SettingsGetReq{Indices: []string{index}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Indices, resp.Inspect().Response) + }) + t.Run("Flush", func(t *testing.T) { + resp, err := client.Indices.Flush(nil, &opensearchapi.IndicesFlushReq{Indices: []string{index}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Forcemerge", func(t *testing.T) { + resp, err := client.Indices.Forcemerge(nil, &opensearchapi.IndicesForcemergeReq{Indices: []string{index}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Clone", func(t *testing.T) { + resp, err := client.Indices.Clone(nil, opensearchapi.IndicesCloneReq{Index: index, Target: indexClone}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Split", func(t *testing.T) { + resp, err := client.Indices.Split( + nil, + opensearchapi.IndicesSplitReq{ + Index: index, + Target: indexSplit, + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":2,"number_of_replicas":0}}}`), + }, + ) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Shrink", func(t *testing.T) { + resp, err := client.Indices.Shrink( + nil, + opensearchapi.IndicesShrinkReq{ + Index: indexSplit, + Target: indexShrink, + Body: strings.NewReader(`{"settings":{"index":{"number_of_shards":1,"number_of_replicas":0}}}`), + }, + ) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Get", func(t *testing.T) { + resp, err := client.Indices.Get(nil, opensearchapi.IndicesGetReq{Indices: []string{index, indexClone}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Indices, resp.Inspect().Response) + }) + t.Run("Recovery", func(t *testing.T) { + resp, err := client.Indices.Recovery(nil, &opensearchapi.IndicesRecoveryReq{Indices: []string{index}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Indices, resp.Inspect().Response) + }) + t.Run("Refresh", func(t *testing.T) { + resp, err := client.Indices.Refresh(nil, &opensearchapi.IndicesRefreshReq{Indices: []string{index}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Segments", func(t *testing.T) { + resp, err := client.Indices.Segments(nil, nil) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("ShardStores", func(t *testing.T) { + resp, err := client.Indices.ShardStores(nil, nil) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Stats", func(t *testing.T) { + resp, err := client.Indices.Stats(nil, nil) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("ValidateQuery", func(t *testing.T) { + resp, err := client.Indices.ValidateQuery( + nil, + opensearchapi.IndicesValidateQueryReq{ + Indices: []string{index}, + Params: opensearchapi.IndicesValidateQueryParams{ + Rewrite: opensearchapi.ToPointer(true), + }, + }, + ) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Count", func(t *testing.T) { + resp, err := client.Indices.Count(nil, nil) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("FieldCaps", func(t *testing.T) { + resp, err := client.Indices.FieldCaps( + nil, + opensearchapi.IndicesFieldCapsReq{ + Params: opensearchapi.IndicesFieldCapsParams{Fields: []string{"*"}}, + }, + ) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Resolve", func(t *testing.T) { + resp, err := client.Indices.Resolve(nil, opensearchapi.IndicesResolveReq{Indices: []string{"*"}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Close", func(t *testing.T) { + resp, err := client.Indices.Close(nil, opensearchapi.IndicesCloseReq{Index: index}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Open", func(t *testing.T) { + resp, err := client.Indices.Open(nil, opensearchapi.IndicesOpenReq{Index: index}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Delete", func(t *testing.T) { + resp, err := client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: testIndices}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + }) +} diff --git a/internal/build/utils/strings.go b/opensearchapi/api_info-params.go similarity index 72% rename from internal/build/utils/strings.go rename to opensearchapi/api_info-params.go index ba7dd31f2..33f4efb50 100644 --- a/internal/build/utils/strings.go +++ b/opensearchapi/api_info-params.go @@ -24,18 +24,29 @@ // specific language governing permissions and limitations // under the License. -package utils +package opensearchapi -import ( - "regexp" -) +// InfoParams represents possible parameters for the InfoReq +type InfoParams struct { + Pretty bool + Human bool + ErrorTrace bool +} -var ( - reIDString = regexp.MustCompile(`\bid\b`) -) +func (r InfoParams) get() map[string]string { + params := make(map[string]string) -// IDToUpper returns a string with all occurrences of "id" capitalized. -// -func IDToUpper(s string) string { - return reIDString.ReplaceAllLiteralString(s, "ID") + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params } diff --git a/opensearchapi/api_info.go b/opensearchapi/api_info.go new file mode 100644 index 000000000..6e228d16b --- /dev/null +++ b/opensearchapi/api_info.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// Info executes a / request with the optional InfoReq +func (c Client) Info(ctx context.Context, req *InfoReq) (*InfoResp, error) { + if req == nil { + req = &InfoReq{} + } + + var ( + data InfoResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// InfoReq represents possible options for the / request +type InfoReq struct { + Header http.Header + Params InfoParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r InfoReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/", + nil, + r.Params.get(), + r.Header, + ) +} + +// InfoResp represents the returned struct of the / response +type InfoResp struct { + Name string `json:"name"` + ClusterName string `json:"cluster_name"` + ClusterUUID string `json:"cluster_uuid"` + Version struct { + Distribution string `json:"distribution"` + Number string `json:"number"` + BuildType string `json:"build_type"` + BuildHash string `json:"build_hash"` + BuildDate string `json:"build_date"` + BuildSnapshot bool `json:"build_snapshot"` + LuceneVersion string `json:"lucene_version"` + MinimumWireCompatibilityVersion string `json:"minimum_wire_compatibility_version"` + MinimumIndexCompatibilityVersion string `json:"minimum_index_compatibility_version"` + } `json:"version"` + Tagline string `json:"tagline"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r InfoResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_info_test.go b/opensearchapi/api_info_test.go new file mode 100644 index 000000000..a4b3771d0 --- /dev/null +++ b/opensearchapi/api_info_test.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestInfo(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + t.Run("with nil request", func(t *testing.T) { + resp, err := client.Info(nil, nil) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("with request", func(t *testing.T) { + resp, err := client.Info(nil, &opensearchapi.InfoReq{}) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.Info(nil, nil) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_ingest-create-params.go b/opensearchapi/api_ingest-create-params.go new file mode 100644 index 000000000..88ebc03ed --- /dev/null +++ b/opensearchapi/api_ingest-create-params.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "time" + +// IngestCreateParams represents possible parameters for the IngestCreateReq +type IngestCreateParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IngestCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_ingest-create.go b/opensearchapi/api_ingest-create.go new file mode 100644 index 000000000..f77f6b1df --- /dev/null +++ b/opensearchapi/api_ingest-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IngestCreateReq represents possible options for the index create request +type IngestCreateReq struct { + PipelineID string + + Body io.Reader + + Header http.Header + Params IngestCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IngestCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_ingest/pipeline/%s", r.PipelineID), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IngestCreateResp represents the returned struct of the index create response +type IngestCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IngestCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_ingest-delete-params.go b/opensearchapi/api_ingest-delete-params.go new file mode 100644 index 000000000..d9144629e --- /dev/null +++ b/opensearchapi/api_ingest-delete-params.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "time" + +// IngestDeleteParams represents possible parameters for the IngestDeleteReq +type IngestDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IngestDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_ingest-delete.go b/opensearchapi/api_ingest-delete.go new file mode 100644 index 000000000..d13b627e9 --- /dev/null +++ b/opensearchapi/api_ingest-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IngestDeleteReq represents possible options for the index create request +type IngestDeleteReq struct { + PipelineID string + + Header http.Header + Params IngestDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IngestDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_ingest/pipeline/%s", r.PipelineID), + nil, + r.Params.get(), + r.Header, + ) +} + +// IngestDeleteResp represents the returned struct of the index create response +type IngestDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IngestDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_ingest-get-params.go b/opensearchapi/api_ingest-get-params.go new file mode 100644 index 000000000..afe8f1c86 --- /dev/null +++ b/opensearchapi/api_ingest-get-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// IngestGetParams represents possible parameters for the IngestGetReq +type IngestGetParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Summary *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IngestGetParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Summary != nil { + params["summary"] = strconv.FormatBool(*r.Summary) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_ingest-get.go b/opensearchapi/api_ingest-get.go new file mode 100644 index 000000000..4f1583ae6 --- /dev/null +++ b/opensearchapi/api_ingest-get.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IngestGetReq represents possible options for the index create request +type IngestGetReq struct { + PipelineIDs []string + + Header http.Header + Params IngestGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IngestGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_ingest/pipeline/%s", strings.Join(r.PipelineIDs, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// IngestGetResp represents the returned struct of the index create response +type IngestGetResp struct { + Pipelines map[string]struct { + Description string `json:"description"` + Processors []map[string]json.RawMessage `json:"processors"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IngestGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_ingest-grok-params.go b/opensearchapi/api_ingest-grok-params.go new file mode 100644 index 000000000..b75987c77 --- /dev/null +++ b/opensearchapi/api_ingest-grok-params.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +// IngestGrokParams represents possible parameters for the IngestGrokReq +type IngestGrokParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IngestGrokParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_ingest-grok.go b/opensearchapi/api_ingest-grok.go new file mode 100644 index 000000000..073a8285e --- /dev/null +++ b/opensearchapi/api_ingest-grok.go @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IngestGrokReq represents possible options for the index create request +type IngestGrokReq struct { + Header http.Header + Params IngestGrokParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IngestGrokReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_ingest/processor/grok", + nil, + r.Params.get(), + r.Header, + ) +} + +// IngestGrokResp represents the returned struct of the index create response +type IngestGrokResp struct { + Patterns map[string]string `json:"patterns"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IngestGrokResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_ingest-simulate-params.go b/opensearchapi/api_ingest-simulate-params.go new file mode 100644 index 000000000..47e36e324 --- /dev/null +++ b/opensearchapi/api_ingest-simulate-params.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import "strconv" + +// IngestSimulateParams represents possible parameters for the IngestSimulateReq +type IngestSimulateParams struct { + Verbose *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r IngestSimulateParams) get() map[string]string { + params := make(map[string]string) + + if r.Verbose != nil { + params["verbose"] = strconv.FormatBool(*r.Verbose) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_ingest-simulate.go b/opensearchapi/api_ingest-simulate.go new file mode 100644 index 000000000..6346b8d9a --- /dev/null +++ b/opensearchapi/api_ingest-simulate.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// IngestSimulateReq represents possible options for the index create request +type IngestSimulateReq struct { + PipelineID string + + Body io.Reader + + Header http.Header + Params IngestSimulateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r IngestSimulateReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("/_ingest/pipeline//_simulate") + len(r.PipelineID)) + path.WriteString("/_ingest/pipeline/") + if len(r.PipelineID) > 0 { + path.WriteString(r.PipelineID) + path.WriteString("/") + } + path.WriteString("_simulate") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// IngestSimulateResp represents the returned struct of the index create response +type IngestSimulateResp struct { + Docs []json.RawMessage `json:"docs"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r IngestSimulateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_ingest.go b/opensearchapi/api_ingest.go new file mode 100644 index 000000000..4734a42ab --- /dev/null +++ b/opensearchapi/api_ingest.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type ingestClient struct { + apiClient *Client +} + +// Create executes a creade ingest request with the required IngestCreateReq +func (c ingestClient) Create(ctx context.Context, req IngestCreateReq) (*IngestCreateResp, error) { + var ( + data IngestCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete ingest request with the required IngestDeleteReq +func (c ingestClient) Delete(ctx context.Context, req IngestDeleteReq) (*IngestDeleteResp, error) { + var ( + data IngestDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get ingest request with the optional IngestGetReq +func (c ingestClient) Get(ctx context.Context, req *IngestGetReq) (*IngestGetResp, error) { + if req == nil { + req = &IngestGetReq{} + } + + var ( + data IngestGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Pipelines); err != nil { + return &data, err + } + + return &data, nil +} + +// Simulate executes a stats ingest request with the optional IngestSimulateReq +func (c ingestClient) Simulate(ctx context.Context, req IngestSimulateReq) (*IngestSimulateResp, error) { + var ( + data IngestSimulateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Grok executes a get ingest request with the optional IngestGrokReq +func (c ingestClient) Grok(ctx context.Context, req *IngestGrokReq) (*IngestGrokResp, error) { + if req == nil { + req = &IngestGrokReq{} + } + + var ( + data IngestGrokResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_ingest_test.go b/opensearchapi/api_ingest_test.go new file mode 100644 index 000000000..a99d7c4dd --- /dev/null +++ b/opensearchapi/api_ingest_test.go @@ -0,0 +1,180 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestIngestClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + ingest := "ingest-test" + + type ingestTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []ingestTests + }{ + { + Name: "Create", + Tests: []ingestTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Ingest.Create( + nil, + opensearchapi.IngestCreateReq{ + PipelineID: ingest, + Body: strings.NewReader(`{"description":"This pipeline processes student data","processors":[{"set":{"description":"Sets the graduation year to 2023","field":"grad_year","value":2023}},{"set":{"description":"Sets graduated to true","field":"graduated","value":true}}]}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Ingest.Create(nil, opensearchapi.IngestCreateReq{}) + }, + }, + }, + }, + { + Name: "Get", + Tests: []ingestTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Ingest.Get(nil, &opensearchapi.IngestGetReq{PipelineIDs: []string{ingest}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Ingest.Get(nil, nil) + }, + }, + }, + }, + { + Name: "Grok", + Tests: []ingestTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Ingest.Grok(nil, nil) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Ingest.Grok(nil, nil) + }, + }, + }, + }, + { + Name: "Simulate", + Tests: []ingestTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Ingest.Simulate( + nil, + opensearchapi.IngestSimulateReq{ + PipelineID: ingest, + Body: strings.NewReader(`{"docs":[{"_index":"my-index","_id":"1","_source":{"grad_year":2024,"graduated":false,"name":"John Doe"}}]}`), + Params: opensearchapi.IngestSimulateParams{Verbose: opensearchapi.ToPointer(true), Pretty: true, Human: true, ErrorTrace: true}, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Ingest.Simulate(nil, opensearchapi.IngestSimulateReq{}) + }, + }, + }, + }, + { + Name: "Delete", + Tests: []ingestTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Ingest.Delete(nil, opensearchapi.IngestDeleteReq{PipelineID: ingest}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Ingest.Delete(nil, opensearchapi.IngestDeleteReq{PipelineID: ingest}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + if value.Name != "Get" { + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + } + }) + } + }) + } + t.Run("ValidateResponse", func(t *testing.T) { + t.Run("Get", func(t *testing.T) { + t.Cleanup(func() { + failingClient.Ingest.Delete(nil, opensearchapi.IngestDeleteReq{PipelineID: ingest}) + }) + _, err := client.Ingest.Create( + nil, + opensearchapi.IngestCreateReq{ + PipelineID: ingest, + Body: strings.NewReader(`{"description":"This pipeline processes student data","processors":[{"set":{"description":"Sets the graduation year to 2023","field":"grad_year","value":2023}},{"set":{"description":"Sets graduated to true","field":"graduated","value":true}}]}`), + }, + ) + require.Nil(t, err) + + resp, err := client.Ingest.Get(nil, nil) + require.Nil(t, err) + require.NotNil(t, resp) + require.NotNil(t, resp.Inspect().Response) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Pipelines, resp.Inspect().Response) + }) + }) +} diff --git a/opensearchapi/api_mget-params.go b/opensearchapi/api_mget-params.go new file mode 100644 index 000000000..f047e18f9 --- /dev/null +++ b/opensearchapi/api_mget-params.go @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// MGetParams represents possible parameters for the MGetReq +type MGetParams struct { + Preference string + Realtime *bool + Refresh *bool + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + StoredFields []string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r MGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.StoredFields) > 0 { + params["stored_fields"] = strings.Join(r.StoredFields, ",") + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_mget.go b/opensearchapi/api_mget.go new file mode 100644 index 000000000..edc071c43 --- /dev/null +++ b/opensearchapi/api_mget.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// MGet executes a /_mget request with the optional MGetReq +func (c Client) MGet(ctx context.Context, req MGetReq) (*MGetResp, error) { + var ( + data MGetResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// MGetReq represents possible options for the /_mget request +type MGetReq struct { + Index string + + Body io.Reader + + Header http.Header + Params MGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MGetReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("//_mget") + len(r.Index)) + if len(r.Index) > 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + path.WriteString("/_mget") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// MGetResp represents the returned struct of the /_mget response +type MGetResp struct { + Docs []struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + Found bool `json:"found"` + Type string `json:"_type"` + Source json.RawMessage `json:"_source"` + } `json:"docs"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_mget_test.go b/opensearchapi/api_mget_test.go new file mode 100644 index 000000000..95a5d9283 --- /dev/null +++ b/opensearchapi/api_mget_test.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestMGet(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testIndex := "test-mget" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + }) + + for i := 1; i <= 2; i++ { + _, err = client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{"foo": "bar"}`), + DocumentID: strconv.Itoa(i), + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + } + + t.Run("with request", func(t *testing.T) { + resp, err := client.MGet( + nil, + opensearchapi.MGetReq{ + Index: testIndex, + Body: strings.NewReader(`{"docs":[{"_id":"1"},{"_id":"2"}]}`), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.MGet(nil, opensearchapi.MGetReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_msearch-params.go b/opensearchapi/api_msearch-params.go new file mode 100644 index 000000000..46741e1c2 --- /dev/null +++ b/opensearchapi/api_msearch-params.go @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" +) + +// MSearchParams represents possible parameters for the MSearchReq +type MSearchParams struct { + CcsMinimizeRoundtrips *bool + MaxConcurrentSearches *int + MaxConcurrentShardRequests *int + PreFilterShardSize *int + RestTotalHitsAsInt *bool + SearchType string + TypedKeys *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r MSearchParams) get() map[string]string { + params := make(map[string]string) + + if r.CcsMinimizeRoundtrips != nil { + params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) + } + + if r.MaxConcurrentSearches != nil { + params["max_concurrent_searches"] = strconv.FormatInt(int64(*r.MaxConcurrentSearches), 10) + } + + if r.MaxConcurrentShardRequests != nil { + params["max_concurrent_shard_requests"] = strconv.FormatInt(int64(*r.MaxConcurrentShardRequests), 10) + } + + if r.PreFilterShardSize != nil { + params["pre_filter_shard_size"] = strconv.FormatInt(int64(*r.PreFilterShardSize), 10) + } + + if r.RestTotalHitsAsInt != nil { + params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.TypedKeys != nil { + params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_msearch-template-params.go b/opensearchapi/api_msearch-template-params.go new file mode 100644 index 000000000..845db9d2f --- /dev/null +++ b/opensearchapi/api_msearch-template-params.go @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" +) + +// MSearchTemplateParams represents possible parameters for the MSearchTemplateReq +type MSearchTemplateParams struct { + CcsMinimizeRoundtrips *bool + MaxConcurrentSearches *int + RestTotalHitsAsInt *bool + SearchType string + TypedKeys *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r MSearchTemplateParams) get() map[string]string { + params := make(map[string]string) + + if r.CcsMinimizeRoundtrips != nil { + params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) + } + + if r.MaxConcurrentSearches != nil { + params["max_concurrent_searches"] = strconv.FormatInt(int64(*r.MaxConcurrentSearches), 10) + } + + if r.RestTotalHitsAsInt != nil { + params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.TypedKeys != nil { + params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_msearch-template.go b/opensearchapi/api_msearch-template.go new file mode 100644 index 000000000..ec1021c20 --- /dev/null +++ b/opensearchapi/api_msearch-template.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// MSearchTemplate executes a /_msearch request with the optional MSearchTemplateReq +func (c Client) MSearchTemplate(ctx context.Context, req MSearchTemplateReq) (*MSearchTemplateResp, error) { + var ( + data MSearchTemplateResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// MSearchTemplateReq represents possible options for the /_msearch request +type MSearchTemplateReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params MSearchTemplateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MSearchTemplateReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("//_msearch/template") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_msearch/template") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// MSearchTemplateResp represents the returned struct of the /_msearch response +type MSearchTemplateResp struct { + Took int `json:"took"` + Responses []struct { + Took int `json:"took"` + Timeout bool `json:"timed_out"` + Shards ResponseShards `json:"_shards"` + Hits struct { + Total struct { + Value int `json:"value"` + Relation string `json:"relation"` + } `json:"total"` + MaxScore *float32 `json:"max_score"` + Hits []SearchHit `json:"hits"` + } `json:"hits"` + Status int `json:"status"` + } `json:"responses"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MSearchTemplateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_msearch-template_test.go b/opensearchapi/api_msearch-template_test.go new file mode 100644 index 000000000..6548a493b --- /dev/null +++ b/opensearchapi/api_msearch-template_test.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestMSearchTemplate(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testIndex := "test-msearch" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + }) + + for i := 1; i <= 2; i++ { + _, err = client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{"foo": "bar"}`), + DocumentID: strconv.Itoa(i), + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + } + + t.Run("with request", func(t *testing.T) { + resp, err := client.MSearchTemplate( + nil, + opensearchapi.MSearchTemplateReq{ + Indices: []string{testIndex}, + Body: strings.NewReader("{}\n{\"source\":{\"query\":{\"exists\":{\"field\":\"{{field}}\"}}},\"params\": {\"field\": \"foo\"}}\n"), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.MSearchTemplate(nil, opensearchapi.MSearchTemplateReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_msearch.go b/opensearchapi/api_msearch.go new file mode 100644 index 000000000..c6bc74097 --- /dev/null +++ b/opensearchapi/api_msearch.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// MSearch executes a /_msearch request with the optional MSearchReq +func (c Client) MSearch(ctx context.Context, req MSearchReq) (*MSearchResp, error) { + var ( + data MSearchResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// MSearchReq represents possible options for the /_msearch request +type MSearchReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params MSearchParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MSearchReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("//_msearch") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_msearch") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// MSearchResp represents the returned struct of the /_msearch response +type MSearchResp struct { + Took int `json:"took"` + Responses []struct { + Took int `json:"took"` + Timeout bool `json:"timed_out"` + Shards ResponseShards `json:"_shards"` + Hits struct { + Total struct { + Value int `json:"value"` + Relation string `json:"relation"` + } `json:"total"` + MaxScore float32 `json:"max_score"` + Hits []SearchHit `json:"hits"` + } `json:"hits"` + Status int `json:"status"` + } `json:"responses"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MSearchResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_msearch_test.go b/opensearchapi/api_msearch_test.go new file mode 100644 index 000000000..052829dc8 --- /dev/null +++ b/opensearchapi/api_msearch_test.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestMSearch(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testIndex := "test-msearch" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + }) + + for i := 1; i <= 2; i++ { + _, err = client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{"foo": "bar"}`), + DocumentID: strconv.Itoa(i), + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + } + + t.Run("with request", func(t *testing.T) { + resp, err := client.MSearch( + nil, + opensearchapi.MSearchReq{ + Indices: []string{testIndex}, + Body: strings.NewReader("{}\n{\"query\":{\"exists\":{\"field\":\"foo\"}}}\n"), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.MSearch(nil, opensearchapi.MSearchReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_mtermvectors-params.go b/opensearchapi/api_mtermvectors-params.go new file mode 100644 index 000000000..cfa2644aa --- /dev/null +++ b/opensearchapi/api_mtermvectors-params.go @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// MTermvectorsParams represents possible parameters for the MTermvectorsReq +type MTermvectorsParams struct { + Fields []string + FieldStatistics *bool + Ids []string + Offsets *bool + Payloads *bool + Positions *bool + Preference string + Realtime *bool + Routing string + TermStatistics *bool + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r MTermvectorsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.Fields) > 0 { + params["fields"] = strings.Join(r.Fields, ",") + } + + if r.FieldStatistics != nil { + params["field_statistics"] = strconv.FormatBool(*r.FieldStatistics) + } + + if len(r.Ids) > 0 { + params["ids"] = strings.Join(r.Ids, ",") + } + + if r.Offsets != nil { + params["offsets"] = strconv.FormatBool(*r.Offsets) + } + + if r.Payloads != nil { + params["payloads"] = strconv.FormatBool(*r.Payloads) + } + + if r.Positions != nil { + params["positions"] = strconv.FormatBool(*r.Positions) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.TermStatistics != nil { + params["term_statistics"] = strconv.FormatBool(*r.TermStatistics) + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_mtermvectors.go b/opensearchapi/api_mtermvectors.go new file mode 100644 index 000000000..2a7679971 --- /dev/null +++ b/opensearchapi/api_mtermvectors.go @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// MTermvectors executes a /_mtermvectors request with the required MTermvectorsReq +func (c Client) MTermvectors(ctx context.Context, req MTermvectorsReq) (*MTermvectorsResp, error) { + var ( + data MTermvectorsResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// MTermvectorsReq represents possible options for the /_mtermvectors request +type MTermvectorsReq struct { + Index string + + Body io.Reader + + Header http.Header + Params MTermvectorsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r MTermvectorsReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("//_mtermvectors") + len(r.Index)) + if len(r.Index) > 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + path.WriteString("/_mtermvectors") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// MTermvectorsResp represents the returned struct of the /_mtermvectors response +type MTermvectorsResp struct { + Docs []struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Found bool `json:"found"` + Took int `json:"took"` + Type string `json:"_type"` // Deprecated field + TermVectors json.RawMessage `json:"term_vectors"` + } `json:"docs"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r MTermvectorsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_mtermvectors_test.go b/opensearchapi/api_mtermvectors_test.go new file mode 100644 index 000000000..496ecffeb --- /dev/null +++ b/opensearchapi/api_mtermvectors_test.go @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestMTermvectors(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testIndex := "test-mtermvectors" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + }) + + _, err = client.Indices.Create( + nil, + opensearchapi.IndicesCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{ "mappings": { + "properties": { + "text": { + "type": "text", + "term_vector": "with_positions_offsets_payloads", + "store" : true, + "analyzer" : "fulltext_analyzer" + }, + "fullname": { + "type": "text", + "term_vector": "with_positions_offsets_payloads", + "analyzer" : "fulltext_analyzer" + } + } + }, + "settings" : { + "index" : { + "number_of_shards" : 1, + "number_of_replicas" : 0 + }, + "analysis": { + "analyzer": { + "fulltext_analyzer": { + "type": "custom", + "tokenizer": "whitespace", + "filter": [ + "lowercase", + "type_as_payload" + ] + } + } + } + } +}`), + }, + ) + require.Nil(t, err) + docs := []string{`{"fullname":"John Doe","text":"test test test "}`, `{"fullname":"Jane Doe","text":"Another test ..."}`} + for i, doc := range docs { + _, err = client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: testIndex, + Body: strings.NewReader(doc), + DocumentID: strconv.Itoa(i), + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + } + + t.Run("with request", func(t *testing.T) { + resp, err := client.MTermvectors( + nil, + opensearchapi.MTermvectorsReq{ + Index: testIndex, + Body: strings.NewReader(`{"ids":[1,2]}`), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.MTermvectors(nil, opensearchapi.MTermvectorsReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_nodes-hot_threads-params.go b/opensearchapi/api_nodes-hot_threads-params.go new file mode 100644 index 000000000..8e2ae4cc9 --- /dev/null +++ b/opensearchapi/api_nodes-hot_threads-params.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// NodesHotThreadsParams represents possible parameters for the NodesHotThreadsReq +type NodesHotThreadsParams struct { + IgnoreIdleThreads *bool + Interval time.Duration + Snapshots *int + Threads *int + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r NodesHotThreadsParams) get() map[string]string { + params := make(map[string]string) + + if r.IgnoreIdleThreads != nil { + params["ignore_idle_threads"] = strconv.FormatBool(*r.IgnoreIdleThreads) + } + + if r.Interval != 0 { + params["interval"] = formatDuration(r.Interval) + } + + if r.Snapshots != nil { + params["snapshots"] = strconv.FormatInt(int64(*r.Snapshots), 10) + } + + if r.Threads != nil { + params["threads"] = strconv.FormatInt(int64(*r.Threads), 10) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_nodes-hot_threads.go b/opensearchapi/api_nodes-hot_threads.go new file mode 100644 index 000000000..1260a0a7d --- /dev/null +++ b/opensearchapi/api_nodes-hot_threads.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// NodesHotThreadsReq represents possible options for the /_nodes request +type NodesHotThreadsReq struct { + NodeID []string + + Header http.Header + Params NodesHotThreadsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r NodesHotThreadsReq) GetRequest() (*http.Request, error) { + nodes := strings.Join(r.NodeID, ",") + + var path strings.Builder + path.Grow(len("/_nodes//hot_threads") + len(nodes)) + path.WriteString("/_nodes/") + if len(r.NodeID) > 0 { + path.WriteString(nodes) + path.WriteString("/") + } + path.WriteString("hot_threads") + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/opensearchapi/api_nodes-info-params.go b/opensearchapi/api_nodes-info-params.go new file mode 100644 index 000000000..73feb40a1 --- /dev/null +++ b/opensearchapi/api_nodes-info-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// NodesInfoParams represents possible parameters for the NodesInfoReq +type NodesInfoParams struct { + FlatSettings *bool + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r NodesInfoParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_nodes-info.go b/opensearchapi/api_nodes-info.go new file mode 100644 index 000000000..c2ccd6929 --- /dev/null +++ b/opensearchapi/api_nodes-info.go @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// NodesInfoReq represents possible options for the /_nodes request +type NodesInfoReq struct { + Metrics []string + NodeID []string + + Header http.Header + Params NodesInfoParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r NodesInfoReq) GetRequest() (*http.Request, error) { + nodes := strings.Join(r.NodeID, ",") + metrics := strings.Join(r.Metrics, ",") + + var path strings.Builder + + path.Grow(len("/_nodes//") + len(nodes) + len(metrics)) + + path.WriteString("/_nodes") + if len(r.NodeID) > 0 { + path.WriteString("/") + path.WriteString(nodes) + } + if len(r.Metrics) > 0 { + path.WriteString("/") + path.WriteString(metrics) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// NodesInfoResp represents the returned struct of the /_nodes response +type NodesInfoResp struct { + NodesInfo struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + Nodes map[string]NodesInfo `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r NodesInfoResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// NodesInfo is a sub type of NodesInfoResp containing information about nodes and their stats +type NodesInfo struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Version string `json:"version"` + BuildType string `json:"build_type"` + BuildHash string `json:"build_hash"` + TotalIndexingBuffer int64 `json:"total_indexing_buffer"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Settings json.RawMessage `json:"settings"` // Won't parse as it may contain fields that we can't know + OS NodesInfoOS `json:"os"` + Process NodesInfoProcess `json:"process"` + JVM NodesInfoJVM `json:"jvm"` + ThreadPool map[string]NodesInfoThreadPool `json:"thread_pool"` + Transport NodesInfoTransport `json:"transport"` + HTTP NodesInfoHTTP `json:"http"` + Plugins []NodesInfoPlugin `json:"plugins"` + Modules []NodesInfoPlugin `json:"modules"` + Ingest NodesInfoIngest `json:"ingest"` + Aggregations map[string]NodesInfoAgg `json:"aggregations"` + SearchPipelines NodesInfoSearchPipelines `json:"search_pipelines"` +} + +// NodesInfoOS is a sub type of NodesInfo containing information about the Operating System +type NodesInfoOS struct { + RefreshIntervalInMillis int `json:"refresh_interval_in_millis"` + Name string `json:"name"` + PrettyName string `json:"pretty_name"` + Arch string `json:"arch"` + Version string `json:"version"` + AvailableProcessors int `json:"available_processors"` + AllocatedProcessors int `json:"allocated_processors"` +} + +// NodesInfoProcess is a sub type of NodesInfo containing information about the nodes process +type NodesInfoProcess struct { + RefreshIntervalInMillis int `json:"refresh_interval_in_millis"` + ID int `json:"id"` + Mlockall bool `json:"mlockall"` +} + +// NodesInfoJVM is a sub type of NodesInfo containing information and stats about JVM +type NodesInfoJVM struct { + PID int `json:"pid"` + Version string `json:"version"` + VMName string `json:"vm_name"` + VMVersion string `json:"vm_version"` + VMVendor string `json:"vm_vendor"` + BundledJDK bool `json:"bundled_jdk"` + UsingBundledJDK bool `json:"using_bundled_jdk"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + Mem struct { + HeapInitInBytes int64 `json:"heap_init_in_bytes"` + HeapMaxInBytes int64 `json:"heap_max_in_bytes"` + NonHeapInitInBytes int `json:"non_heap_init_in_bytes"` + NonHeapMaxInBytes int `json:"non_heap_max_in_bytes"` + DirectMaxInBytes int `json:"direct_max_in_bytes"` + } `json:"mem"` + GcCollectors []string `json:"gc_collectors"` + MemoryPools []string `json:"memory_pools"` + UsingCompressedOrdinaryObjectPointers string `json:"using_compressed_ordinary_object_pointers"` + InputArguments []string `json:"input_arguments"` +} + +// NodesInfoThreadPool is a sub type of NodesInfo containing information about a thread pool +type NodesInfoThreadPool struct { + Type string `json:"type"` + Size int `json:"size"` + QueueSize int `json:"queue_size"` + KeepAlive string `json:"keep_alive"` + Max int `json:"max"` + Core int `json:"core"` +} + +// NodesInfoTransport is a sub type of NodesInfo containing information about the nodes transport settings +type NodesInfoTransport struct { + BoundAddress []string `json:"bound_address"` + PublishAddress string `json:"publish_address"` + Profiles json.RawMessage `json:"profiles"` // Unknown content +} + +// NodesInfoHTTP is a sub type of NodesInfo containing information about the nodes http settings +type NodesInfoHTTP struct { + BoundAddress []string `json:"bound_address"` + PublishAddress string `json:"publish_address"` + MaxContentLengthInBytes int64 `json:"max_content_length_in_bytes"` +} + +// NodesInfoPlugin is a sub type of NodesInfo containing information about a plugin +type NodesInfoPlugin struct { + Name string `json:"name"` + Version string `json:"version"` + OpensearchVersion string `json:"opensearch_version"` + JavaVersion string `json:"java_version"` + Description string `json:"description"` + Classname string `json:"classname"` + CustomFoldername string `json:"custom_foldername"` + ExtendedPlugins []string `json:"extended_plugins"` + HasNativeController bool `json:"has_native_controller"` +} + +// NodesInfoIngest is a sub type of NodesInfo containing information about ingest processors +type NodesInfoIngest struct { + Processors []NodesInfoType `json:"processors"` +} + +// NodesInfoAgg is a sub type of NodesInfo containing information about aggregations +type NodesInfoAgg struct { + Types []string `json:"types"` +} + +// NodesInfoSearchPipelines is a sub type of NodesInfo containing information about search pipelines +type NodesInfoSearchPipelines struct { + RequestProcessors []NodesInfoType `json:"request_processors"` + ResponseProcessors []NodesInfoType `json:"response_processors"` + Processors []NodesInfoType `json:"processors,omitempty"` // Deprecated field only available in 2.7.0 +} + +// NodesInfoType is a sub type of NodesInfoIngest, NodesInfoSearchPipelines containing information about a type +type NodesInfoType struct { + Type string `json:"type"` +} diff --git a/opensearchapi/api_nodes-reload_security-params.go b/opensearchapi/api_nodes-reload_security-params.go new file mode 100644 index 000000000..b1fb04051 --- /dev/null +++ b/opensearchapi/api_nodes-reload_security-params.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// NodesReloadSecurityParams represents possible parameters for the NodesReloadSecurityReq +type NodesReloadSecurityParams struct { + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r NodesReloadSecurityParams) get() map[string]string { + params := make(map[string]string) + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_nodes-reload_security.go b/opensearchapi/api_nodes-reload_security.go new file mode 100644 index 000000000..79dc77fe8 --- /dev/null +++ b/opensearchapi/api_nodes-reload_security.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// NodesReloadSecurityReq represents possible options for the /_nodes request +type NodesReloadSecurityReq struct { + NodeID []string + + Body io.Reader + + Header http.Header + Params NodesReloadSecurityParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r NodesReloadSecurityReq) GetRequest() (*http.Request, error) { + nodes := strings.Join(r.NodeID, ",") + + var path strings.Builder + + path.Grow(len("/_nodes//reload_secure_settings") + len(nodes)) + + path.WriteString("/_nodes") + if len(r.NodeID) > 0 { + path.WriteString("/") + path.WriteString(nodes) + } + path.WriteString("/reload_secure_settings") + + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// NodesReloadSecurityResp represents the returned struct of the /_nodes response +type NodesReloadSecurityResp struct { + NodesInfo struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + Nodes map[string]struct { + Name string `json:"name"` + } `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r NodesReloadSecurityResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_nodes-stats-params.go b/opensearchapi/api_nodes-stats-params.go new file mode 100644 index 000000000..b9f592bfb --- /dev/null +++ b/opensearchapi/api_nodes-stats-params.go @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// NodesStatsParams represents possible parameters for the NodesStatsReq +type NodesStatsParams struct { + CompletionFields []string + FielddataFields []string + Fields []string + Groups *bool + IncludeSegmentFileSizes *bool + IncludeUnloadedSegments *bool + Level string + Timeout time.Duration + Types []string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r NodesStatsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.CompletionFields) > 0 { + params["completion_fields"] = strings.Join(r.CompletionFields, ",") + } + + if len(r.FielddataFields) > 0 { + params["fielddata_fields"] = strings.Join(r.FielddataFields, ",") + } + + if len(r.Fields) > 0 { + params["fields"] = strings.Join(r.Fields, ",") + } + + if r.Groups != nil { + params["groups"] = strconv.FormatBool(*r.Groups) + } + + if r.IncludeSegmentFileSizes != nil { + params["include_segment_file_sizes"] = strconv.FormatBool(*r.IncludeSegmentFileSizes) + } + + if r.IncludeUnloadedSegments != nil { + params["include_unloaded_segments"] = strconv.FormatBool(*r.IncludeUnloadedSegments) + } + + if r.Level != "" { + params["level"] = r.Level + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if len(r.Types) > 0 { + params["types"] = strings.Join(r.Types, ",") + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_nodes-stats.go b/opensearchapi/api_nodes-stats.go new file mode 100644 index 000000000..217c8fa8d --- /dev/null +++ b/opensearchapi/api_nodes-stats.go @@ -0,0 +1,723 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// NodesStatsReq represents possible options for the /_nodes request +type NodesStatsReq struct { + IndexMetric []string + Metric []string + NodeID []string + Header http.Header + Params NodesStatsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r NodesStatsReq) GetRequest() (*http.Request, error) { + var path strings.Builder + + path.Grow(13 + len(strings.Join(r.NodeID, ",")) + 1 + len(strings.Join(r.Metric, ",")) + 1 + len(strings.Join(r.IndexMetric, ","))) + + path.WriteString("/") + path.WriteString("_nodes") + + if len(r.NodeID) > 0 { + path.WriteString("/") + path.WriteString(strings.Join(r.NodeID, ",")) + } + + path.WriteString("/") + path.WriteString("stats") + + if len(r.Metric) > 0 { + path.WriteString("/") + path.WriteString(strings.Join(r.Metric, ",")) + } + + if len(r.IndexMetric) > 0 { + path.WriteString("/") + path.WriteString(strings.Join(r.IndexMetric, ",")) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// NodesStatsResp represents the returned struct of the /_nodes response +type NodesStatsResp struct { + NodesInfo struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + Nodes map[string]NodesStats `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r NodesStatsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// NodesStats is a map item of NodesStatsResp representing all values of a node +type NodesStats struct { + Timestamp int `json:"timestamp"` + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Indices NodesStatsIndices `json:"indices"` + OS NodesStatsOS `json:"os"` + Process NodesStatsProcess `json:"process"` + JVM NodesStatsJVM `json:"jvm"` + ThreadPool NodesStatsThreadPool `json:"thread_pool"` + FS NodesStatsFS `json:"fs"` + Transport NodesStatsTransport `json:"transport"` + HTTP NodesStatsHTTP `json:"http"` + Breakers NodesStatsBreakers `json:"breakers"` + Scripts NodesStatsScript `json:"script"` + Discovery NodesStatsDiscovery `json:"discovery"` + Ingest NodesStatsIngest `json:"ingest"` + AdaptiveSelection NodesStatsAdaptiveSelection `json:"adaptive_selection"` + ScriptCache NodesStatsScriptCache `json:"script_cache"` + IndexingPressure NodesStatsIndexingPressure `json:"indexing_pressure"` + ShardIndexingPressure NodesStatsShardIndexingPressure `json:"shard_indexing_pressure"` + SearchBackpressure NodesStatsSearchBackpressure `json:"search_backpressure"` + ClusterManagerThrottling NodesStatsClusterManagerThrottling `json:"cluster_manager_throttling"` + WeightedRouting NodesStatsWeightedRouting `json:"weighted_routing"` + SearchPipeline NodesStatsSearchPipeline `json:"search_pipeline"` + TaskCancellation NodesStatsTaskCancellation `json:"task_cancellation"` +} + +// NodesStatsIndices is a sub type of NodesStats representing Indices information of the node +type NodesStatsIndices struct { + Docs struct { + Count int `json:"count"` + Deleted int `json:"deleted"` + } `json:"docs"` + Store struct { + SizeInBytes int `json:"size_in_bytes"` + ReservedInBytes int `json:"reserved_in_bytes"` + } `json:"store"` + Indexing struct { + IndexTotal int `json:"index_total"` + IndexTimeInMillis int `json:"index_time_in_millis"` + IndexCurrent int `json:"index_current"` + IndexFailed int `json:"index_failed"` + DeleteTotal int `json:"delete_total"` + DeleteTimeInMillis int `json:"delete_time_in_millis"` + DeleteCurrent int `json:"delete_current"` + NoopUpdateTotal int `json:"noop_update_total"` + IsThrottled bool `json:"is_throttled"` + ThrottleTimeInMillis int `json:"throttle_time_in_millis"` + DocStatus map[string]int `json:"doc_status"` + } `json:"indexing"` + Get struct { + Total int `json:"total"` + TimeInMillis int `json:"time_in_millis"` + ExistsTotal int `json:"exists_total"` + ExistsTimeInMillis int `json:"exists_time_in_millis"` + MissingTotal int `json:"missing_total"` + MissingTimeInMillis int `json:"missing_time_in_millis"` + Current int `json:"current"` + } `json:"get"` + Search struct { + OpenContexts int `json:"open_contexts"` + QueryTotal int `json:"query_total"` + QueryTimeInMillis int `json:"query_time_in_millis"` + QueryCurrent int `json:"query_current"` + FetchTotal int `json:"fetch_total"` + FetchTimeInMillis int `json:"fetch_time_in_millis"` + FetchCurrent int `json:"fetch_current"` + ScrollTotal int `json:"scroll_total"` + ScrollTimeInMillis int `json:"scroll_time_in_millis"` + ScrollCurrent int `json:"scroll_current"` + PointInTimeTotal int `json:"point_in_time_total"` + PointInTimeTimeInMillis int `json:"point_in_time_time_in_millis"` + PointInTimeCurrent int `json:"point_in_time_current"` + SuggestTotal int `json:"suggest_total"` + SuggestTimeInMillis int `json:"suggest_time_in_millis"` + SuggestCurrent int `json:"suggest_current"` + Request struct { + DfsPreQuery NodesStatsIndicesSearchRequest `json:"dfs_pre_query"` + Query NodesStatsIndicesSearchRequest `json:"query"` + Fetch NodesStatsIndicesSearchRequest `json:"fetch"` + DfsQuery NodesStatsIndicesSearchRequest `json:"dfs_query"` + Expand NodesStatsIndicesSearchRequest `json:"expand"` + CanMatch NodesStatsIndicesSearchRequest `json:"can_match"` + } `json:"request"` + } `json:"search"` + Merges struct { + Current int `json:"current"` + CurrentDocs int `json:"current_docs"` + CurrentSizeInBytes int `json:"current_size_in_bytes"` + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` + TotalDocs int `json:"total_docs"` + TotalSizeInBytes int `json:"total_size_in_bytes"` + TotalStoppedTimeInMillis int `json:"total_stopped_time_in_millis"` + TotalThrottledTimeInMillis int `json:"total_throttled_time_in_millis"` + TotalAutoThrottleInBytes int `json:"total_auto_throttle_in_bytes"` + UnreferencedFileCleanupsPerformed int `json:"unreferenced_file_cleanups_performed"` + } `json:"merges"` + Refresh struct { + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` + ExternalTotal int `json:"external_total"` + ExternalTotalTimeInMillis int `json:"external_total_time_in_millis"` + Listeners int `json:"listeners"` + } `json:"refresh"` + Flush struct { + Total int `json:"total"` + Periodic int `json:"periodic"` + TotalTimeInMillis int `json:"total_time_in_millis"` + } `json:"flush"` + Warmer struct { + Current int `json:"current"` + Total int `json:"total"` + TotalTimeInMillis int `json:"total_time_in_millis"` + } `json:"warmer"` + QueryCache struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + TotalCount int `json:"total_count"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` + CacheSize int `json:"cache_size"` + CacheCount int `json:"cache_count"` + Evictions int `json:"evictions"` + } `json:"query_cache"` + Fielddata struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + Evictions int `json:"evictions"` + } `json:"fielddata"` + Completion struct { + SizeInBytes int `json:"size_in_bytes"` + } `json:"completion"` + Segments struct { + Count int `json:"count"` + MemoryInBytes int `json:"memory_in_bytes"` + TermsMemoryInBytes int `json:"terms_memory_in_bytes"` + StoredFieldsMemoryInBytes int `json:"stored_fields_memory_in_bytes"` + TermVectorsMemoryInBytes int `json:"term_vectors_memory_in_bytes"` + NormsMemoryInBytes int `json:"norms_memory_in_bytes"` + PointsMemoryInBytes int `json:"points_memory_in_bytes"` + DocValuesMemoryInBytes int `json:"doc_values_memory_in_bytes"` + IndexWriterMemoryInBytes int `json:"index_writer_memory_in_bytes"` + VersionMapMemoryInBytes int `json:"version_map_memory_in_bytes"` + FixedBitSetMemoryInBytes int `json:"fixed_bit_set_memory_in_bytes"` + MaxUnsafeAutoIDTimestamp int `json:"max_unsafe_auto_id_timestamp"` + RemoteStore struct { + Upload struct { + TotalUploadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_upload_size"` + RefreshSizeLag struct { + TotalBytes int `json:"total_bytes"` + MaxBytes int `json:"max_bytes"` + } `json:"refresh_size_lag"` + MaxRefreshTimeLagInMillis int `json:"max_refresh_time_lag_in_millis"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + } `json:"upload"` + Download struct { + TotalDownloadSize struct { + StartedBytes int `json:"started_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + FailedBytes int `json:"failed_bytes"` + } `json:"total_download_size"` + TotalTimeSpentInMillis int `json:"total_time_spent_in_millis"` + } `json:"download"` + } `json:"remote_store"` + SegmentReplication struct { + // Type is json.RawMessage due to difference in opensearch versions from string to int + MaxBytesBehind json.RawMessage `json:"max_bytes_behind"` + TotalBytesBehind json.RawMessage `json:"total_bytes_behind"` + MaxReplicationLag json.RawMessage `json:"max_replication_lag"` + } `json:"segment_replication"` + FileSizes json.RawMessage `json:"file_sizes"` + } `json:"segments"` + Translog struct { + Operations int `json:"operations"` + SizeInBytes int `json:"size_in_bytes"` + UncommittedOperations int `json:"uncommitted_operations"` + UncommittedSizeInBytes int `json:"uncommitted_size_in_bytes"` + EarliestLastModifiedAge int `json:"earliest_last_modified_age"` + RemoteStore struct { + Upload struct { + TotalUploads struct { + Started int `json:"started"` + Failed int `json:"failed"` + Succeeded int `json:"succeeded"` + } `json:"total_uploads"` + TotalUploadSize struct { + StartedBytes int `json:"started_bytes"` + FailedBytes int `json:"failed_bytes"` + SucceededBytes int `json:"succeeded_bytes"` + } `json:"total_upload_size"` + } `json:"upload"` + } `json:"remote_store"` + } `json:"translog"` + RequestCache struct { + MemorySizeInBytes int `json:"memory_size_in_bytes"` + Evictions int `json:"evictions"` + HitCount int `json:"hit_count"` + MissCount int `json:"miss_count"` + } `json:"request_cache"` + Recovery struct { + CurrentAsSource int `json:"current_as_source"` + CurrentAsTarget int `json:"current_as_target"` + ThrottleTimeInMillis int `json:"throttle_time_in_millis"` + } `json:"recovery"` +} + +// NodesStatsOS is a sub type of NodesStats representing operating system information of the node +type NodesStatsOS struct { + Timestamp int `json:"timestamp"` + CPU struct { + Percent int `json:"percent"` + LoadAverage struct { + OneM float64 `json:"1m"` + FiveM float64 `json:"5m"` + One5M float64 `json:"15m"` + } `json:"load_average"` + } `json:"cpu"` + Mem struct { + TotalInBytes int `json:"total_in_bytes"` + FreeInBytes int `json:"free_in_bytes"` + UsedInBytes int `json:"used_in_bytes"` + FreePercent int `json:"free_percent"` + UsedPercent int `json:"used_percent"` + } `json:"mem"` + Swap struct { + TotalInBytes int `json:"total_in_bytes"` + FreeInBytes int `json:"free_in_bytes"` + UsedInBytes int `json:"used_in_bytes"` + } `json:"swap"` +} + +// NodesStatsProcess is a sub type of NodesStats representing processor information of the node +type NodesStatsProcess struct { + Timestamp int `json:"timestamp"` + OpenFileDescriptors int `json:"open_file_descriptors"` + MaxFileDescriptors int `json:"max_file_descriptors"` + CPU struct { + Percent int `json:"percent"` + TotalInMillis int `json:"total_in_millis"` + } `json:"cpu"` + Mem struct { + TotalVirtualInBytes int `json:"total_virtual_in_bytes"` + } `json:"mem"` +} + +// NodesStatsJVMPool is a sub type of NodesStatsJVM represeting all information a pool can have +type NodesStatsJVMPool struct { + UsedInBytes int `json:"used_in_bytes"` + MaxInBytes int `json:"max_in_bytes"` + PeakUsedInBytes int `json:"peak_used_in_bytes"` + PeakMaxInBytes int `json:"peak_max_in_bytes"` + LastGcStats struct { + UsedInBytes int `json:"used_in_bytes"` + MaxInBytes int `json:"max_in_bytes"` + UsagePercent int `json:"usage_percent"` + } `json:"last_gc_stats"` +} + +// NodesStatsJVMBufferPool is a sub map type represeting all information a buffer pool can have +type NodesStatsJVMBufferPool struct { + Count int `json:"count"` + UsedInBytes int `json:"used_in_bytes"` + TotalCapacityInBytes int `json:"total_capacity_in_bytes"` +} + +// NodesStatsJVM is a sub type of NodesStats representing java virtual maschine information of the node +type NodesStatsJVM struct { + Timestamp int `json:"timestamp"` + UptimeInMillis int `json:"uptime_in_millis"` + Mem struct { + HeapUsedInBytes int `json:"heap_used_in_bytes"` + HeapUsedPercent int `json:"heap_used_percent"` + HeapCommittedInBytes int `json:"heap_committed_in_bytes"` + HeapMaxInBytes int `json:"heap_max_in_bytes"` + NonHeapUsedInBytes int `json:"non_heap_used_in_bytes"` + NonHeapCommittedInBytes int `json:"non_heap_committed_in_bytes"` + Pools struct { + Young NodesStatsJVMPool `json:"young"` + Old NodesStatsJVMPool `json:"old"` + Survivor NodesStatsJVMPool `json:"survivor"` + } `json:"pools"` + } `json:"mem"` + Threads struct { + Count int `json:"count"` + PeakCount int `json:"peak_count"` + } `json:"threads"` + Gc struct { + Collectors struct { + Young struct { + CollectionCount int `json:"collection_count"` + CollectionTimeInMillis int `json:"collection_time_in_millis"` + } `json:"young"` + Old struct { + CollectionCount int `json:"collection_count"` + CollectionTimeInMillis int `json:"collection_time_in_millis"` + } `json:"old"` + } `json:"collectors"` + } `json:"gc"` + // Not parsing each field directly as one of them contains singe quotes which are not allowed as tag in golang json + // https://github.com/golang/go/issues/22518 + BufferPools map[string]NodesStatsJVMBufferPool `json:"buffer_pools"` + Classes struct { + CurrentLoadedCount int `json:"current_loaded_count"` + TotalLoadedCount int `json:"total_loaded_count"` + TotalUnloadedCount int `json:"total_unloaded_count"` + } `json:"classes"` +} + +// NodesStatsThreadPoolValues is a sub type of NodesStatsThreadPool representing all information a thread pool can have +type NodesStatsThreadPoolValues struct { + Threads int `json:"threads"` + Queue int `json:"queue"` + Active int `json:"active"` + Rejected int `json:"rejected"` + Largest int `json:"largest"` + Completed int `json:"completed"` +} + +// NodesStatsThreadPoolValuesSearch is a sub type of NodesStatsThreadPool representing all information a search thread pool can have +type NodesStatsThreadPoolValuesSearch struct { + Threads int `json:"threads"` + Queue int `json:"queue"` + Active int `json:"active"` + Rejected int `json:"rejected"` + Largest int `json:"largest"` + Completed int `json:"completed"` + TotalWaitTimeInNanos int64 `json:"total_wait_time_in_nanos"` +} + +// NodesStatsThreadPool is a sub type of NodesStats representing thread pool information of the node +type NodesStatsThreadPool struct { + AdBatchTaskThreadpool NodesStatsThreadPoolValues `json:"ad-batch-task-threadpool"` + AdThreadpool NodesStatsThreadPoolValues `json:"ad-threadpool"` + Analyze NodesStatsThreadPoolValues `json:"analyze"` + FetchShardStarted NodesStatsThreadPoolValues `json:"fetch_shard_started"` + FetchShardStore NodesStatsThreadPoolValues `json:"fetch_shard_store"` + Flush NodesStatsThreadPoolValues `json:"flush"` + ForceMerge NodesStatsThreadPoolValues `json:"force_merge"` + Generic NodesStatsThreadPoolValues `json:"generic"` + Get NodesStatsThreadPoolValues `json:"get"` + Listener NodesStatsThreadPoolValues `json:"listener"` + Management NodesStatsThreadPoolValues `json:"management"` + OpenDistroJobScheduler NodesStatsThreadPoolValues `json:"open_distro_job_scheduler"` + OpensearchAsynchronousSearchGeneric NodesStatsThreadPoolValues `json:"opensearch_asynchronous_search_generic"` + OpensearchMLTask NodesStatsThreadPoolValues `json:"OPENSEARCH_ML_TASK_THREAD_POOL"` + OpensearchMlDeploy NodesStatsThreadPoolValues `json:"opensearch_ml_deploy"` + OpensearchMlExecute NodesStatsThreadPoolValues `json:"opensearch_ml_execute"` + OpensearchMlGeneral NodesStatsThreadPoolValues `json:"opensearch_ml_general"` + OpensearchMlLoad NodesStatsThreadPoolValues `json:"opensearch_ml_load"` + OpensearchMlPredict NodesStatsThreadPoolValues `json:"opensearch_ml_predict"` + OpensearchMlRegister NodesStatsThreadPoolValues `json:"opensearch_ml_register"` + OpensearchMlTrain NodesStatsThreadPoolValues `json:"opensearch_ml_train"` + OpensearchMlUpload NodesStatsThreadPoolValues `json:"opensearch_ml_upload"` + Refresh NodesStatsThreadPoolValues `json:"refresh"` + RemotePurge NodesStatsThreadPoolValues `json:"remote_purge"` + RemoteRefresh NodesStatsThreadPoolValues `json:"remote_refresh"` + ReplicationFollower NodesStatsThreadPoolValues `json:"replication_follower"` + ReplicationLeader NodesStatsThreadPoolValues `json:"replication_leader"` + Search NodesStatsThreadPoolValuesSearch `json:"search"` + SearchThrottled NodesStatsThreadPoolValuesSearch `json:"search_throttled"` + Snapshot NodesStatsThreadPoolValues `json:"snapshot"` + SQLWorker NodesStatsThreadPoolValues `json:"sql-worker"` + SystemRead NodesStatsThreadPoolValues `json:"system_read"` + SystemWrite NodesStatsThreadPoolValues `json:"system_write"` + Training NodesStatsThreadPoolValues `json:"training"` + TranslogSync NodesStatsThreadPoolValues `json:"translog_sync"` + TranslogTransfer NodesStatsThreadPoolValues `json:"translog_transfer"` + Warmer NodesStatsThreadPoolValues `json:"warmer"` + Write NodesStatsThreadPoolValues `json:"write"` + PluginGeospatialIP2GeoDatasourceUpdate NodesStatsThreadPoolValues `json:"_plugin_geospatial_ip2geo_datasource_update"` + RemoteRefreshRetry NodesStatsThreadPoolValues `json:"remote_refresh_retry"` + RemoteRecovery NodesStatsThreadPoolValues `json:"remote_recovery"` +} + +// NodesStatsFS is a sub type of NodesStats representing filesystem information of the node +type NodesStatsFS struct { + Timestamp int `json:"timestamp"` + Total struct { + TotalInBytes int `json:"total_in_bytes"` + FreeInBytes int `json:"free_in_bytes"` + AvailableInBytes int `json:"available_in_bytes"` + CacheReservedInBytes int `json:"cache_reserved_in_bytes"` + } `json:"total"` + Data []struct { + Path string `json:"path"` + Mount string `json:"mount"` + Type string `json:"type"` + TotalInBytes int `json:"total_in_bytes"` + FreeInBytes int `json:"free_in_bytes"` + AvailableInBytes int `json:"available_in_bytes"` + CacheReservedInBytes int `json:"cache_reserved_in_bytes"` + } `json:"data"` + IoStats struct { + Devices []struct { + DeviceName string `json:"device_name"` + Operations int `json:"operations"` + ReadOperations int `json:"read_operations"` + WriteOperations int `json:"write_operations"` + ReadKilobytes int `json:"read_kilobytes"` + WriteKilobytes int `json:"write_kilobytes"` + } `json:"devices"` + Total struct { + Operations int `json:"operations"` + ReadOperations int `json:"read_operations"` + WriteOperations int `json:"write_operations"` + ReadKilobytes int `json:"read_kilobytes"` + WriteKilobytes int `json:"write_kilobytes"` + } `json:"total"` + } `json:"io_stats"` +} + +// NodesStatsTransport is a sub type of NodesStats representing network transport information of the node +type NodesStatsTransport struct { + ServerOpen int `json:"server_open"` + TotalOutboundConnections int `json:"total_outbound_connections"` + RxCount int `json:"rx_count"` + RxSizeInBytes int `json:"rx_size_in_bytes"` + TxCount int `json:"tx_count"` + TxSizeInBytes int `json:"tx_size_in_bytes"` +} + +// NodesStatsHTTP is a sub type of NodesStats representing http information of the node +type NodesStatsHTTP struct { + CurrentOpen int `json:"current_open"` + TotalOpened int `json:"total_opened"` +} + +// NodesStatsBreaker is a sub type of NodesStatsBreakers containing all information a breaker can have +type NodesStatsBreaker struct { + LimitSizeInBytes int `json:"limit_size_in_bytes"` + LimitSize string `json:"limit_size"` + EstimatedSizeInBytes int `json:"estimated_size_in_bytes"` + EstimatedSize string `json:"estimated_size"` + Overhead float64 `json:"overhead"` + Tripped int `json:"tripped"` +} + +// NodesStatsBreakers is a sub type of NodesStats representing breakers information of the node +type NodesStatsBreakers struct { + Accounting NodesStatsBreaker `json:"accounting"` + Request NodesStatsBreaker `json:"request"` + Fielddata NodesStatsBreaker `json:"fielddata"` + InFlightRequests NodesStatsBreaker `json:"in_flight_requests"` + Parent NodesStatsBreaker `json:"parent"` +} + +// NodesStatsScript is a sub type of NodesStats representing script information of the node +type NodesStatsScript struct { + Compilations int `json:"compilations"` + CacheEvictions int `json:"cache_evictions"` + CompilationLimitTriggered int `json:"compilation_limit_triggered"` +} + +// NodesStatsDiscovery is a sub type of NodesStats representing discovery information of the node +type NodesStatsDiscovery struct { + ClusterStateQueue struct { + Total int `json:"total"` + Pending int `json:"pending"` + Committed int `json:"committed"` + } `json:"cluster_state_queue"` + PublishedClusterStates struct { + FullStates int `json:"full_states"` + IncompatibleDiffs int `json:"incompatible_diffs"` + CompatibleDiffs int `json:"compatible_diffs"` + } `json:"published_cluster_states"` +} + +// NodesStatsIngestDetails is a sub map type of NodsStatsIngest containing all information of ingest pipelines +type NodesStatsIngestDetails struct { + Count int `json:"count"` + TimeInMillis int `json:"time_in_millis"` + Failed int `json:"failed"` + Current int `json:"current"` + Processors []json.RawMessage `json:"processors"` +} + +// NodesStatsIngest is a sub type of NodesStats representing ingest pipelines information of the node +type NodesStatsIngest struct { + Total struct { + Count int `json:"count"` + TimeInMillis int `json:"time_in_millis"` + Current int `json:"current"` + Failed int `json:"failed"` + } `json:"total"` + Pipelines map[string]NodesStatsIngestDetails `json:"pipelines"` +} + +// NodesStatsAdaptiveSelection is a sub type of NodesStats representing adaptive selection information of the node +type NodesStatsAdaptiveSelection map[string]struct { + OutgoingSearches int `json:"outgoing_searches"` + AvgQueueSize int `json:"avg_queue_size"` + AvgServiceTimeNs int `json:"avg_service_time_ns"` + AvgResponseTimeNs int `json:"avg_response_time_ns"` + Rank string `json:"rank"` +} + +// NodesStatsScriptCache is a sub type of NodesStats representing script cache information of the node +type NodesStatsScriptCache struct { + Sum struct { + Compilations int `json:"compilations"` + CacheEvictions int `json:"cache_evictions"` + CompilationLimitTriggered int `json:"compilation_limit_triggered"` + } `json:"sum"` + Contexts []struct { + Context string `json:"context"` + Compilations int `json:"compilations"` + CacheEvictions int `json:"cache_evictions"` + CompilationLimitTriggered int `json:"compilation_limit_triggered"` + } `json:"contexts"` +} + +// NodesStatsIndexingPressure is a sub type of NodesStats representing indexing pressure information of the node +type NodesStatsIndexingPressure struct { + Memory struct { + Current struct { + CombinedCoordinatingAndPrimaryInBytes int `json:"combined_coordinating_and_primary_in_bytes"` + CoordinatingInBytes int `json:"coordinating_in_bytes"` + PrimaryInBytes int `json:"primary_in_bytes"` + ReplicaInBytes int `json:"replica_in_bytes"` + AllInBytes int `json:"all_in_bytes"` + } `json:"current"` + Total struct { + CombinedCoordinatingAndPrimaryInBytes int `json:"combined_coordinating_and_primary_in_bytes"` + CoordinatingInBytes int `json:"coordinating_in_bytes"` + PrimaryInBytes int `json:"primary_in_bytes"` + ReplicaInBytes int `json:"replica_in_bytes"` + AllInBytes int `json:"all_in_bytes"` + CoordinatingRejections int `json:"coordinating_rejections"` + PrimaryRejections int `json:"primary_rejections"` + ReplicaRejections int `json:"replica_rejections"` + } `json:"total"` + LimitInBytes int `json:"limit_in_bytes"` + } `json:"memory"` +} + +// NodesStatsShardIndexingPressure is a sub type of NodesStats representing shard indexing pressure information of the node +type NodesStatsShardIndexingPressure struct { + Stats json.RawMessage `json:"stats"` // Unknown, can be added if you have an example + TotalRejectionsBreakupShadowMode struct { + NodeLimits int `json:"node_limits"` + NoSuccessfulRequestLimits int `json:"no_successful_request_limits"` + ThroughputDegradationLimits int `json:"throughput_degradation_limits"` + } `json:"total_rejections_breakup_shadow_mode"` + Enabled bool `json:"enabled"` + Enforced bool `json:"enforced"` +} + +// NodesStatsSearchBackpressureTracker is a sub type of NodesStatsSearchBrackpressure containing all information of a tracker +type NodesStatsSearchBackpressureTracker struct { + CancellationCount int `json:"cancellation_count"` + CurrentMaxMillis int `json:"current_max_millis"` + CurrentAvgMillis int `json:"current_avg_millis"` +} + +// NodesStatsSearchBackpressure is a sub type of NodesStats representing search packbressure information of a node +type NodesStatsSearchBackpressure struct { + SearchTask struct { + ResourceTrackerStats struct { + CPUUsageTracker NodesStatsSearchBackpressureTracker `json:"cpu_usage_tracker"` + ElapsedTimeTracker NodesStatsSearchBackpressureTracker `json:"elapsed_time_tracker"` + HeapUsageTracker struct { + CancellationCount int `json:"cancellation_count"` + CurrentMaxBytes int `json:"current_max_bytes"` + CurrentAvgBytes int `json:"current_avg_bytes"` + RollingAvgBytes int `json:"rolling_avg_bytes"` + } `json:"heap_usage_tracker"` + } `json:"resource_tracker_stats"` + CancellationStats struct { + CancellationCount int `json:"cancellation_count"` + CancellationLimitReachedCount int `json:"cancellation_limit_reached_count"` + } `json:"cancellation_stats"` + } `json:"search_task"` + SearchShardTask struct { + ResourceTrackerStats struct { + CPUUsageTracker NodesStatsSearchBackpressureTracker `json:"cpu_usage_tracker"` + ElapsedTimeTracker NodesStatsSearchBackpressureTracker `json:"elapsed_time_tracker"` + HeapUsageTracker struct { + CancellationCount int `json:"cancellation_count"` + CurrentMaxBytes int `json:"current_max_bytes"` + CurrentAvgBytes int `json:"current_avg_bytes"` + RollingAvgBytes int `json:"rolling_avg_bytes"` + } `json:"heap_usage_tracker"` + } `json:"resource_tracker_stats"` + CancellationStats struct { + CancellationCount int `json:"cancellation_count"` + CancellationLimitReachedCount int `json:"cancellation_limit_reached_count"` + } `json:"cancellation_stats"` + } `json:"search_shard_task"` + Mode string `json:"mode"` +} + +// NodesStatsClusterManagerThrottling is a sub type of NodesStats representing cluster manager throttling information of the node +type NodesStatsClusterManagerThrottling struct { + Stats struct { + TotalThrottledTasks int `json:"total_throttled_tasks"` + ThrottledTasksPerTaskType json.RawMessage `json:"throttled_tasks_per_task_type"` // Unknow struct, no example in doc + } `json:"stats"` +} + +// NodesStatsWeightedRouting is a sub type of NodesStats representing weighted routing information of the node +type NodesStatsWeightedRouting struct { + Stats struct { + FailOpenCount int `json:"fail_open_count"` + } `json:"stats"` +} + +// NodesStatsSearchPipeline is a sub type of NodesStats containing stats about search pipelines +type NodesStatsSearchPipeline struct { + TotalRequest struct { + Count int `json:"count"` + TimeInMillis int `json:"time_in_millis"` + Current int `json:"current"` + Failed int `json:"failed"` + } `json:"total_request"` + TotalResponse struct { + Count int `json:"count"` + TimeInMillis int `json:"time_in_millis"` + Current int `json:"current"` + Failed int `json:"failed"` + } `json:"total_response"` + Pipelines json.RawMessage `json:"pipelines"` +} + +// NodesStatsTaskCancellation is a sub type of NodesStats containing stats about canceled tasks +type NodesStatsTaskCancellation struct { + SearchShardTask struct { + CurrentCountPostCancel int `json:"current_count_post_cancel"` + TotalCountPostCancel int `json:"total_count_post_cancel"` + } `json:"search_shard_task"` +} + +// NodesStatsIndicesSearchRequest is a sub type of NodesStatsIndices containing stats about search requests +type NodesStatsIndicesSearchRequest struct { + TimeInMillis int `json:"time_in_millis"` + Current int `json:"current"` + Total int `json:"total"` +} diff --git a/internal/build/utils/map.go b/opensearchapi/api_nodes-usage-params.go similarity index 66% rename from internal/build/utils/map.go rename to opensearchapi/api_nodes-usage-params.go index 8bba53db0..a1e2fd4f1 100644 --- a/internal/build/utils/map.go +++ b/opensearchapi/api_nodes-usage-params.go @@ -24,28 +24,39 @@ // specific language governing permissions and limitations // under the License. -package utils +package opensearchapi -// MapKeys returns the map keys as a slice of strings. -// -func MapKeys(s interface{}) (keys []string) { - if s, ok := s.(map[interface{}]interface{}); ok { - for k := range s { - if k, ok := k.(string); ok { - keys = append(keys, k) - } - } - } - return keys +import ( + "time" +) + +// NodesUsageParams represents possible parameters for the NodesUsageReq +type NodesUsageParams struct { + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool } -// MapValues returns the map values as a slice of interfaces. -// -func MapValues(s interface{}) (values []interface{}) { - if s, ok := s.(map[interface{}]interface{}); ok { - for _, v := range s { - values = append(values, v) - } +func (r NodesUsageParams) get() map[string]string { + params := make(map[string]string) + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) } - return values + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params } diff --git a/opensearchapi/api_nodes-usage.go b/opensearchapi/api_nodes-usage.go new file mode 100644 index 000000000..5b1b13fdf --- /dev/null +++ b/opensearchapi/api_nodes-usage.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// NodesUsageReq represents possible options for the /_nodes request +type NodesUsageReq struct { + Metrics []string + NodeID []string + + Header http.Header + Params NodesUsageParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r NodesUsageReq) GetRequest() (*http.Request, error) { + nodes := strings.Join(r.NodeID, ",") + metrics := strings.Join(r.Metrics, ",") + + var path strings.Builder + + path.Grow(len("/_nodes//usage/") + len(nodes) + len(metrics)) + + path.WriteString("/_nodes") + if len(r.NodeID) > 0 { + path.WriteString("/") + path.WriteString(nodes) + } + path.WriteString("/usage") + if len(r.Metrics) > 0 { + path.WriteString("/") + path.WriteString(metrics) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// NodesUsageResp represents the returned struct of the /_nodes response +type NodesUsageResp struct { + NodesUsage struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_nodes"` + ClusterName string `json:"cluster_name"` + Nodes map[string]NodesUsage `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r NodesUsageResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// NodesUsage is a sub type of NodesUsageResp containing stats about rest api actions +type NodesUsage struct { + Timestamp int64 `json:"timestamp"` + Since int64 `json:"since"` + RestActions map[string]int `json:"rest_actions"` + Aggregations json.RawMessage `json:"aggregations"` // Can contain unknow fields +} diff --git a/opensearchapi/api_nodes.go b/opensearchapi/api_nodes.go new file mode 100644 index 000000000..7c2002ddb --- /dev/null +++ b/opensearchapi/api_nodes.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v2" +) + +type nodesClient struct { + apiClient *Client +} + +// Stats executes a /_nodes/_stats request with the optional NodesStatsReq +func (c nodesClient) Stats(ctx context.Context, req *NodesStatsReq) (*NodesStatsResp, error) { + if req == nil { + req = &NodesStatsReq{} + } + + var ( + data NodesStatsResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Info executes a /_nodes request with the optional NodesInfoReq +func (c nodesClient) Info(ctx context.Context, req *NodesInfoReq) (*NodesInfoResp, error) { + if req == nil { + req = &NodesInfoReq{} + } + + var ( + data NodesInfoResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// HotThreads executes a /_nodes/hot_threads request with the optional NodesHotThreadsReq +func (c nodesClient) HotThreads(ctx context.Context, req *NodesHotThreadsReq) (*opensearch.Response, error) { + if req == nil { + req = &NodesHotThreadsReq{} + } + return c.apiClient.do(ctx, req, nil) +} + +// ReloadSecurity executes a /_nodes/reload_secure_settings request with the optional NodesReloadSecurityReq +func (c nodesClient) ReloadSecurity(ctx context.Context, req *NodesReloadSecurityReq) (*NodesReloadSecurityResp, error) { + if req == nil { + req = &NodesReloadSecurityReq{} + } + + var ( + data NodesReloadSecurityResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Usage executes a /_nodes/usage request with the optional NodesUsageReq +func (c nodesClient) Usage(ctx context.Context, req *NodesUsageReq) (*NodesUsageResp, error) { + if req == nil { + req = &NodesUsageReq{} + } + + var ( + data NodesUsageResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_nodes_test.go b/opensearchapi/api_nodes_test.go new file mode 100644 index 000000000..1d08efae3 --- /dev/null +++ b/opensearchapi/api_nodes_test.go @@ -0,0 +1,188 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestNodes(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + type nodesTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []nodesTests + }{ + { + Name: "Stats", + Tests: []nodesTests{ + { + Name: "without request", + Results: func() (osapitest.Response, error) { + return client.Nodes.Stats(nil, nil) + }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Nodes.Stats(nil, &opensearchapi.NodesStatsReq{NodeID: []string{"*"}, Metric: []string{"indices"}, IndexMetric: []string{"store"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Nodes.Stats(nil, nil) + }, + }, + }, + }, + { + Name: "Info", + Tests: []nodesTests{ + { + Name: "without request", + Results: func() (osapitest.Response, error) { + return client.Nodes.Info(nil, nil) + }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Nodes.Info(nil, &opensearchapi.NodesInfoReq{NodeID: []string{"*"}, Metrics: []string{"settings", "os"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Nodes.Info(nil, nil) + }, + }, + }, + }, + { + Name: "HotThreads", + Tests: []nodesTests{ + { + Name: "without request", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = client.Nodes.HotThreads(nil, nil) + return resp, err + }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = client.Nodes.HotThreads(nil, &opensearchapi.NodesHotThreadsReq{NodeID: []string{"*"}}) + return resp, err + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = failingClient.Nodes.HotThreads(nil, nil) + return resp, err + }, + }, + }, + }, + { + Name: "ReloadSecurity", + Tests: []nodesTests{ + { + Name: "without request", + Results: func() (osapitest.Response, error) { + return client.Nodes.ReloadSecurity(nil, nil) + }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Nodes.ReloadSecurity(nil, &opensearchapi.NodesReloadSecurityReq{NodeID: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Nodes.ReloadSecurity(nil, nil) + }, + }, + }, + }, + { + Name: "Usage", + Tests: []nodesTests{ + { + Name: "without request", + Results: func() (osapitest.Response, error) { + return client.Nodes.Usage(nil, nil) + }, + }, + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Nodes.Usage(nil, &opensearchapi.NodesUsageReq{NodeID: []string{"*"}, Metrics: []string{"*"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Nodes.Usage(nil, nil) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + if value.Name != "HotThreads" { + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + } + }) + } + }) + } +} diff --git a/internal/build/cmd/generate/commands/genexamples/skips.go b/opensearchapi/api_ping-params.go similarity index 72% rename from internal/build/cmd/generate/commands/genexamples/skips.go rename to opensearchapi/api_ping-params.go index 8504fa660..fd0e44f45 100644 --- a/internal/build/cmd/generate/commands/genexamples/skips.go +++ b/opensearchapi/api_ping-params.go @@ -24,8 +24,29 @@ // specific language governing permissions and limitations // under the License. -package genexamples +package opensearchapi -var skipPatterns = []string{ - `size=surprise_me`, // Size must be numeric +// PingParams represents possible parameters for the PingReq +type PingParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r PingParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params } diff --git a/opensearchapi/api_ping.go b/opensearchapi/api_ping.go new file mode 100644 index 000000000..5fd5a86e5 --- /dev/null +++ b/opensearchapi/api_ping.go @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// Ping executes a / request with the optional PingReq +func (c Client) Ping(ctx context.Context, req *PingReq) (*opensearch.Response, error) { + if req == nil { + req = &PingReq{} + } + + return c.do(ctx, req, nil) +} + +// PingReq represents possible options for the / request +type PingReq struct { + Header http.Header + Params PingParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r PingReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + "/", + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/opensearchapi/api_ping_test.go b/opensearchapi/api_ping_test.go new file mode 100644 index 000000000..9ed35749e --- /dev/null +++ b/opensearchapi/api_ping_test.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestPing(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + t.Run("with nil request", func(t *testing.T) { + resp, err := client.Ping(nil, nil) + require.Nil(t, err) + assert.NotEmpty(t, resp) + }) + + t.Run("with request", func(t *testing.T) { + resp, err := client.Ping(nil, &opensearchapi.PingReq{}) + require.Nil(t, err) + assert.NotEmpty(t, resp) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + var ( + resp dummyInspect + ) + resp.response, err = failingClient.Ping(nil, nil) + assert.NotNil(t, err) + assert.NotNil(t, resp) + osapitest.VerifyInspect(t, resp.Inspect()) + }) +} diff --git a/opensearchapi/api_point_in_time-create-params.go b/opensearchapi/api_point_in_time-create-params.go new file mode 100644 index 000000000..2fc653fcd --- /dev/null +++ b/opensearchapi/api_point_in_time-create-params.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "time" +) + +// PointInTimeCreateParams represents possible parameters for the PointInTimeCreateReq +type PointInTimeCreateParams struct { + KeepAlive time.Duration + Preference string + Routing string + ExpandWildcards string + AllowPartialPitCreation bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r PointInTimeCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.KeepAlive != 0 { + params["keep_alive"] = formatDuration(r.KeepAlive) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.AllowPartialPitCreation { + params["allow_partial_pit_creation"] = "true" + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_point_in_time-create.go b/opensearchapi/api_point_in_time-create.go new file mode 100644 index 000000000..5ddefd1df --- /dev/null +++ b/opensearchapi/api_point_in_time-create.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// PointInTimeCreateReq represents possible options for the index create request +type PointInTimeCreateReq struct { + Indices []string + + Header http.Header + Params PointInTimeCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r PointInTimeCreateReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + + var path strings.Builder + path.Grow(len("//_search/point_in_time") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_search/point_in_time") + + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// PointInTimeCreateResp represents the returned struct of the index create response +type PointInTimeCreateResp struct { + PitID string `json:"pit_id"` + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Skipped int `json:"skipped"` + Failed int `json:"failed"` + } `json:"_shards"` + CreationTime int64 `json:"creation_time"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r PointInTimeCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_point_in_time-delete-params.go b/opensearchapi/api_point_in_time-delete-params.go new file mode 100644 index 000000000..2e7680a0c --- /dev/null +++ b/opensearchapi/api_point_in_time-delete-params.go @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +// PointInTimeDeleteParams represents possible parameters for the PointInTimeDeleteReq +type PointInTimeDeleteParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r PointInTimeDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_point_in_time-delete.go b/opensearchapi/api_point_in_time-delete.go new file mode 100644 index 000000000..a932f6f05 --- /dev/null +++ b/opensearchapi/api_point_in_time-delete.go @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// PointInTimeDeleteReq represents possible options for the index create request +type PointInTimeDeleteReq struct { + PitID []string + + Header http.Header + Params PointInTimeDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r PointInTimeDeleteReq) GetRequest() (*http.Request, error) { + var body io.Reader + if len(r.PitID) > 0 { + bodyStruct := PointInTimeDeleteRequestBody{PitID: r.PitID} + bodyJSON, err := json.Marshal(bodyStruct) + if err != nil { + return nil, err + } + body = bytes.NewBuffer(bodyJSON) + } + + return opensearch.BuildRequest( + "DELETE", + "/_search/point_in_time", + body, + r.Params.get(), + r.Header, + ) +} + +// PointInTimeDeleteRequestBody is used to from the delete request body +type PointInTimeDeleteRequestBody struct { + PitID []string `json:"pit_id"` +} + +// PointInTimeDeleteResp represents the returned struct of the index create response +type PointInTimeDeleteResp struct { + Pits []struct { + PitID string `json:"pit_id"` + Successful bool `json:"successful"` + } `json:"pits"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r PointInTimeDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_point_in_time-get-params.go b/opensearchapi/api_point_in_time-get-params.go new file mode 100644 index 000000000..4b4bfa3f8 --- /dev/null +++ b/opensearchapi/api_point_in_time-get-params.go @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +// PointInTimeGetParams represents possible parameters for the PointInTimeGetReq +type PointInTimeGetParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r PointInTimeGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_point_in_time-get.go b/opensearchapi/api_point_in_time-get.go new file mode 100644 index 000000000..753835903 --- /dev/null +++ b/opensearchapi/api_point_in_time-get.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// PointInTimeGetReq represents possible options for the index create request +type PointInTimeGetReq struct { + Header http.Header + Params PointInTimeGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r PointInTimeGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_search/point_in_time/_all", + nil, + r.Params.get(), + r.Header, + ) +} + +// PointInTimeGetResp represents the returned struct of the index create response +type PointInTimeGetResp struct { + Pits []struct { + PitID string `json:"pit_id"` + CreationTime int `json:"creation_time"` + KeepAlive int64 `json:"keep_alive"` + } `json:"pits"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r PointInTimeGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_point_in_time.go b/opensearchapi/api_point_in_time.go new file mode 100644 index 000000000..bc1a80af7 --- /dev/null +++ b/opensearchapi/api_point_in_time.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type pointInTimeClient struct { + apiClient *Client +} + +// Create executes a creade pointInTime request with the required PointInTimeCreateReq +func (c pointInTimeClient) Create(ctx context.Context, req PointInTimeCreateReq) (*PointInTimeCreateResp, error) { + var ( + data PointInTimeCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete pointInTime request with the required PointInTimeDeleteReq +func (c pointInTimeClient) Delete(ctx context.Context, req PointInTimeDeleteReq) (*PointInTimeDeleteResp, error) { + var ( + data PointInTimeDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get pointInTime request with the optional PointInTimeGetReq +func (c pointInTimeClient) Get(ctx context.Context, req *PointInTimeGetReq) (*PointInTimeGetResp, error) { + if req == nil { + req = &PointInTimeGetReq{} + } + + var ( + data PointInTimeGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_point_in_time_test.go b/opensearchapi/api_point_in_time_test.go new file mode 100644 index 000000000..278d9331d --- /dev/null +++ b/opensearchapi/api_point_in_time_test.go @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestPointInTimeClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + osapitest.SkipIfBelowVersion(t, client, 2, 4, "Point_In_Time") + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + pitID := "" + + type pointInTimeTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []pointInTimeTests + }{ + { + Name: "Create", + Tests: []pointInTimeTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + keepAlive, _ := time.ParseDuration("5m") + resp, err := client.PointInTime.Create( + nil, + opensearchapi.PointInTimeCreateReq{ + Indices: []string{"*"}, + Params: opensearchapi.PointInTimeCreateParams{KeepAlive: keepAlive}, + }, + ) + pitID = resp.PitID + return resp, err + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.PointInTime.Create(nil, opensearchapi.PointInTimeCreateReq{}) + }, + }, + }, + }, + { + Name: "Get", + Tests: []pointInTimeTests{ + { + Name: "without request", + Results: func() (osapitest.Response, error) { + return client.PointInTime.Get(nil, nil) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.PointInTime.Get(nil, nil) + }, + }, + }, + }, + { + Name: "Delete", + Tests: []pointInTimeTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.PointInTime.Delete(nil, opensearchapi.PointInTimeDeleteReq{PitID: []string{pitID}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.PointInTime.Delete(nil, opensearchapi.PointInTimeDeleteReq{}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + }) + } + }) + } +} diff --git a/opensearchapi/api_rank_eval-params.go b/opensearchapi/api_rank_eval-params.go new file mode 100644 index 000000000..5741b01f5 --- /dev/null +++ b/opensearchapi/api_rank_eval-params.go @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" +) + +// RankEvalParams represents possible parameters for the RankEvalReq +type RankEvalParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + SearchType string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r RankEvalParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_rank_eval.go b/opensearchapi/api_rank_eval.go new file mode 100644 index 000000000..cdde0c126 --- /dev/null +++ b/opensearchapi/api_rank_eval.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// RankEval executes a /_rank_eval request with the required RankEvalReq +func (c Client) RankEval(ctx context.Context, req RankEvalReq) (*RankEvalResp, error) { + var ( + data RankEvalResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// RankEvalReq represents possible options for the /_rank_eval request +type RankEvalReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params RankEvalParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r RankEvalReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("//_rank_eval") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_rank_eval") + return opensearch.BuildRequest( + "GET", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// RankEvalResp represents the returned struct of the /_rank_eval response +type RankEvalResp struct { + MetricScore float64 `json:"metric_score"` + Details json.RawMessage `json:"details"` + Failures json.RawMessage `json:"failures"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r RankEvalResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_rank_eval_test.go b/opensearchapi/api_rank_eval_test.go new file mode 100644 index 000000000..19b1e3a9a --- /dev/null +++ b/opensearchapi/api_rank_eval_test.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestRankEval(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testIndex := "test-rank_eval" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + }) + + for i := 1; i <= 2; i++ { + _, err = client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{"foo": "bar"}`), + DocumentID: strconv.Itoa(i), + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + } + + t.Run("with request", func(t *testing.T) { + resp, err := client.RankEval( + nil, + opensearchapi.RankEvalReq{ + Indices: []string{testIndex}, + Body: strings.NewReader(`{"requests":[{"id":"test","request":{"query":{"match_all":{}}},"ratings":[]}],"metric":{"expected_reciprocal_rank":{"maximum_relevance":3,"k":20}}}`), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.RankEval(nil, opensearchapi.RankEvalReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_reindex-params.go b/opensearchapi/api_reindex-params.go new file mode 100644 index 000000000..177392d36 --- /dev/null +++ b/opensearchapi/api_reindex-params.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "fmt" + "strconv" + "time" +) + +// ReindexParams represents possible parameters for the ReindexReq +type ReindexParams struct { + MaxDocs *int + Refresh *bool + RequestsPerSecond *int + Scroll time.Duration + Slices interface{} + Timeout time.Duration + WaitForActiveShards string + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ReindexParams) get() map[string]string { + params := make(map[string]string) + + if r.MaxDocs != nil { + params["max_docs"] = strconv.FormatInt(int64(*r.MaxDocs), 10) + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.Slices != nil { + params["slices"] = fmt.Sprintf("%v", r.Slices) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_reindex.go b/opensearchapi/api_reindex.go new file mode 100644 index 000000000..b1860e325 --- /dev/null +++ b/opensearchapi/api_reindex.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// Reindex executes a / request with the optional ReindexReq +func (c Client) Reindex(ctx context.Context, req ReindexReq) (*ReindexResp, error) { + var ( + data ReindexResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// ReindexReq represents possible options for the / request +type ReindexReq struct { + Body io.Reader + + Header http.Header + Params ReindexParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ReindexReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_reindex", + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ReindexResp represents the returned struct of the / response +type ReindexResp struct { + Took int `json:"took"` + TimedOut bool `json:"timed_out"` + Total int `json:"total"` + Updated int `json:"updated"` + Created int `json:"created"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float64 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + Failures []json.RawMessage `json:"failures"` + Task string `json:"task"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ReindexResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/internal/build/main.go b/opensearchapi/api_reindex_rethrottle-params.go similarity index 64% rename from internal/build/main.go rename to opensearchapi/api_reindex_rethrottle-params.go index a4f713168..9f85e171c 100644 --- a/internal/build/main.go +++ b/opensearchapi/api_reindex_rethrottle-params.go @@ -24,18 +24,39 @@ // specific language governing permissions and limitations // under the License. -package main +package opensearchapi import ( - "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd" - - _ "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd/generate/commands/genexamples" - _ "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd/generate/commands/gensource" - _ "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd/generate/commands/genstruct" - _ "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd/generate/commands/gentests" - _ "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd/tools/commands/spec" + "strconv" ) -func main() { - cmd.Execute() +// ReindexRethrottleParams represents possible parameters for the ReindexRethrottleReq +type ReindexRethrottleParams struct { + RequestsPerSecond *int + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ReindexRethrottleParams) get() map[string]string { + params := make(map[string]string) + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params } diff --git a/opensearchapi/api_reindex_rethrottle.go b/opensearchapi/api_reindex_rethrottle.go new file mode 100644 index 000000000..c4ac6e684 --- /dev/null +++ b/opensearchapi/api_reindex_rethrottle.go @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ReindexRethrottle executes a / request with the optional ReindexRethrottleReq +func (c Client) ReindexRethrottle(ctx context.Context, req ReindexRethrottleReq) (*ReindexRethrottleResp, error) { + var ( + data ReindexRethrottleResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// ReindexRethrottleReq represents possible options for the / request +type ReindexRethrottleReq struct { + TaskID string + + Header http.Header + Params ReindexRethrottleParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ReindexRethrottleReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_reindex/%s/_rethrottle", r.TaskID), + nil, + r.Params.get(), + r.Header, + ) +} + +// ReindexRethrottleResp represents the returned struct of the / response +type ReindexRethrottleResp struct { + Nodes map[string]struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Tasks map[string]struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + Status struct { + Total int `json:"total"` + Updated int `json:"updated"` + Created int `json:"created"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float64 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + } `json:"status"` + Description string `json:"description"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers json.RawMessage `json:"headers"` + ResourceStats struct { + Average struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"average"` + Total struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"total"` + Min struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"min"` + Max struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"max"` + ThreadInfo struct { + ThreadExecutions int `json:"thread_executions"` + ActiveThreads int `json:"active_threads"` + } `json:"thread_info"` + } `json:"resource_stats"` + } `json:"tasks"` + } `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ReindexRethrottleResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_reindex_rethrottle_test.go b/opensearchapi/api_reindex_rethrottle_test.go new file mode 100644 index 000000000..3060bb5d7 --- /dev/null +++ b/opensearchapi/api_reindex_rethrottle_test.go @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "context" + "fmt" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" + "github.com/opensearch-project/opensearch-go/v2/opensearchutil" +) + +func TestReindexRethrottle(t *testing.T) { + t.Parallel() + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + sourceIndex := "test-reindex-rethrottle-source" + destIndex := "test-reindex-rethrottle-dest" + testIndices := []string{sourceIndex, destIndex} + t.Cleanup(func() { + client.Indices.Delete( + nil, + opensearchapi.IndicesDeleteReq{ + Indices: testIndices, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + }) + + for _, index := range testIndices { + client.Indices.Create( + nil, + opensearchapi.IndicesCreateReq{ + Index: index, + Body: strings.NewReader(`{"settings": {"number_of_shards": 1, "number_of_replicas": 0}}`), + }, + ) + } + bi, err := opensearchutil.NewBulkIndexer(opensearchutil.BulkIndexerConfig{ + Index: sourceIndex, + Client: client, + Refresh: "wait_for", + }) + for i := 1; i <= 60; i++ { + err := bi.Add(context.Background(), opensearchutil.BulkIndexerItem{ + Action: "index", + DocumentID: strconv.Itoa(i), + Body: strings.NewReader(`{"title":"bar"}`), + }) + if err != nil { + t.Fatalf("Unexpected error: %s", err) + } + } + if err := bi.Close(context.Background()); err != nil { + t.Errorf("Unexpected error: %s", err) + } + + reindex, err := client.Reindex( + nil, + opensearchapi.ReindexReq{ + Body: strings.NewReader(fmt.Sprintf(`{"source":{"index":"%s","size":1},"dest":{"index":"%s"}}`, sourceIndex, destIndex)), + Params: opensearchapi.ReindexParams{ + WaitForCompletion: opensearchapi.ToPointer(false), + RequestsPerSecond: opensearchapi.ToPointer(1), + }, + }, + ) + require.Nil(t, err) + t.Run("with request", func(t *testing.T) { + resp, err := client.ReindexRethrottle( + nil, + opensearchapi.ReindexRethrottleReq{ + TaskID: reindex.Task, + Params: opensearchapi.ReindexRethrottleParams{RequestsPerSecond: opensearchapi.ToPointer(40)}, + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.ReindexRethrottle(nil, opensearchapi.ReindexRethrottleReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_reindex_test.go b/opensearchapi/api_reindex_test.go new file mode 100644 index 000000000..dc0d4fe72 --- /dev/null +++ b/opensearchapi/api_reindex_test.go @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "context" + "fmt" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" + "github.com/opensearch-project/opensearch-go/v2/opensearchutil" +) + +func TestReindex(t *testing.T) { + t.Parallel() + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + sourceIndex := "test-reindex-source" + destIndex := "test-reindex-dest" + testIndices := []string{sourceIndex, destIndex} + t.Cleanup(func() { + client.Indices.Delete( + nil, + opensearchapi.IndicesDeleteReq{ + Indices: testIndices, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + }) + + for _, index := range testIndices { + client.Indices.Create( + nil, + opensearchapi.IndicesCreateReq{ + Index: index, + Body: strings.NewReader(`{"settings": {"number_of_shards": 1, "number_of_replicas": 0}}`), + }, + ) + } + + bi, err := opensearchutil.NewBulkIndexer(opensearchutil.BulkIndexerConfig{ + Index: sourceIndex, + Client: client, + Refresh: "wait_for", + }) + for i := 1; i <= 100; i++ { + err := bi.Add(context.Background(), opensearchutil.BulkIndexerItem{ + Action: "index", + DocumentID: strconv.Itoa(i), + Body: strings.NewReader(`{"title":"bar"}`), + }) + if err != nil { + t.Fatalf("Unexpected error: %s", err) + } + } + if err := bi.Close(context.Background()); err != nil { + t.Errorf("Unexpected error: %s", err) + } + + t.Run("with request", func(t *testing.T) { + resp, err := client.Reindex( + nil, + opensearchapi.ReindexReq{ + Body: strings.NewReader(fmt.Sprintf(`{"source":{"index":"%s"},"dest":{"index":"%s"}}`, sourceIndex, destIndex)), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("with request but dont wait", func(t *testing.T) { + resp, err := client.Reindex( + nil, + opensearchapi.ReindexReq{ + Body: strings.NewReader(fmt.Sprintf(`{"source":{"index":"%s"},"dest":{"index":"%s"}}`, sourceIndex, destIndex)), + Params: opensearchapi.ReindexParams{WaitForCompletion: opensearchapi.ToPointer(false)}, + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.Reindex(nil, opensearchapi.ReindexReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_render_search_template-params.go b/opensearchapi/api_render_search_template-params.go new file mode 100644 index 000000000..b979ba5d1 --- /dev/null +++ b/opensearchapi/api_render_search_template-params.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +// RenderSearchTemplateParams represents possible parameters for the RenderSearchTemplateReq +type RenderSearchTemplateParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r RenderSearchTemplateParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_render_search_template.go b/opensearchapi/api_render_search_template.go new file mode 100644 index 000000000..57805e760 --- /dev/null +++ b/opensearchapi/api_render_search_template.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// RenderSearchTemplate executes a /_render/template request with the required RenderSearchTemplateReq +func (c Client) RenderSearchTemplate(ctx context.Context, req RenderSearchTemplateReq) (*RenderSearchTemplateResp, error) { + var ( + data RenderSearchTemplateResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// RenderSearchTemplateReq represents possible options for the /_render/template request +type RenderSearchTemplateReq struct { + TemplateID string + + Body io.Reader + + Header http.Header + Params RenderSearchTemplateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r RenderSearchTemplateReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("//_render/template") + len(r.TemplateID)) + path.WriteString("/_render/template") + if len(r.TemplateID) > 0 { + path.WriteString("/") + path.WriteString(r.TemplateID) + } + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// RenderSearchTemplateResp represents the returned struct of the /_render/template response +type RenderSearchTemplateResp struct { + TemplateOutput json.RawMessage `json:"template_output"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r RenderSearchTemplateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_render_search_template_test.go b/opensearchapi/api_render_search_template_test.go new file mode 100644 index 000000000..1a3fe73c7 --- /dev/null +++ b/opensearchapi/api_render_search_template_test.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestRenderSearchTemplate(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testScript := "test-search-template" + t.Cleanup(func() { + client.Script.Delete(nil, opensearchapi.ScriptDeleteReq{ScriptID: testScript}) + }) + + _, err = client.Script.Put( + nil, + opensearchapi.ScriptPutReq{ + ScriptID: testScript, + Body: strings.NewReader(`{"script":{"lang":"mustache","source":{"from":"{{from}}{{^from}}0{{/from}}","size":"{{size}}{{^size}}10{{/size}}","query":{"match":{"play_name":""}}},"params":{"play_name":"Henry IV"}}}`), + }, + ) + require.Nil(t, err) + + t.Run("with request", func(t *testing.T) { + resp, err := client.RenderSearchTemplate( + nil, + opensearchapi.RenderSearchTemplateReq{ + TemplateID: testScript, + Body: strings.NewReader(fmt.Sprintf(`{"id":"%s","params":{"play_name":"Henry IV"}}`, testScript)), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.RenderSearchTemplate(nil, opensearchapi.RenderSearchTemplateReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_script-context-params.go b/opensearchapi/api_script-context-params.go new file mode 100644 index 000000000..acaf417be --- /dev/null +++ b/opensearchapi/api_script-context-params.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +// ScriptContextParams represents possible parameters for the ScriptContextReq +type ScriptContextParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ScriptContextParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_script-context.go b/opensearchapi/api_script-context.go new file mode 100644 index 000000000..0233ba5f0 --- /dev/null +++ b/opensearchapi/api_script-context.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ScriptContextReq represents possible options for the delete script request +type ScriptContextReq struct { + Header http.Header + Params ScriptContextParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptContextReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_script_context", + nil, + r.Params.get(), + r.Header, + ) +} + +// ScriptContextResp represents the returned struct of the delete script response +type ScriptContextResp struct { + Contexts []struct { + Name string `json:"name"` + Methods []struct { + Name string `json:"name"` + ReturnType string `json:"return_type"` + Params []struct { + Name string `json:"name"` + Type string `json:"type"` + } `json:"params"` + } `json:"methods"` + } `json:"contexts"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptContextResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_script-delete-params.go b/opensearchapi/api_script-delete-params.go new file mode 100644 index 000000000..b456780fb --- /dev/null +++ b/opensearchapi/api_script-delete-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// ScriptDeleteParams represents possible parameters for the ScriptDeleteReq +type ScriptDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ScriptDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_script-delete.go b/opensearchapi/api_script-delete.go new file mode 100644 index 000000000..a2bffd46c --- /dev/null +++ b/opensearchapi/api_script-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ScriptDeleteReq represents possible options for the delete script request +type ScriptDeleteReq struct { + ScriptID string + + Header http.Header + Params ScriptDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_scripts/%s", r.ScriptID), + nil, + r.Params.get(), + r.Header, + ) +} + +// ScriptDeleteResp represents the returned struct of the delete script response +type ScriptDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_script-get-params.go b/opensearchapi/api_script-get-params.go new file mode 100644 index 000000000..1ec6ac2d0 --- /dev/null +++ b/opensearchapi/api_script-get-params.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// ScriptGetParams represents possible parameters for the ScriptGetReq +type ScriptGetParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ScriptGetParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_script-get.go b/opensearchapi/api_script-get.go new file mode 100644 index 000000000..e2df8c12f --- /dev/null +++ b/opensearchapi/api_script-get.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ScriptGetReq represents possible options for the get script request +type ScriptGetReq struct { + ScriptID string + + Header http.Header + Params ScriptGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_scripts/%s", r.ScriptID), + nil, + r.Params.get(), + r.Header, + ) +} + +// ScriptGetResp represents the returned struct of the get script response +type ScriptGetResp struct { + ID string `json:"_id"` + Found bool `json:"found"` + Script struct { + Lang string `json:"lang"` + Source string `json:"source"` + } `json:"script"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_script-language-params.go b/opensearchapi/api_script-language-params.go new file mode 100644 index 000000000..544a78fe6 --- /dev/null +++ b/opensearchapi/api_script-language-params.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +// ScriptLanguageParams represents possible parameters for the ScriptLanguageReq +type ScriptLanguageParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ScriptLanguageParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_script-language.go b/opensearchapi/api_script-language.go new file mode 100644 index 000000000..76ff88db2 --- /dev/null +++ b/opensearchapi/api_script-language.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ScriptLanguageReq represents possible options for the delete script request +type ScriptLanguageReq struct { + Header http.Header + Params ScriptLanguageParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptLanguageReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_script_language", + nil, + r.Params.get(), + r.Header, + ) +} + +// ScriptLanguageResp represents the returned struct of the delete script response +type ScriptLanguageResp struct { + TypesAllowed []string `json:"types_allowed"` + LanguageContexts []struct { + Language string `json:"language"` + Contexts []string `json:"contexts"` + } `json:"language_contexts"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptLanguageResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_script-painless_execute-params.go b/opensearchapi/api_script-painless_execute-params.go new file mode 100644 index 000000000..44c2c7b51 --- /dev/null +++ b/opensearchapi/api_script-painless_execute-params.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +// ScriptPainlessExecuteParams represents possible parameters for the ScriptPainlessExecuteReq +type ScriptPainlessExecuteParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ScriptPainlessExecuteParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_script-painless_execute.go b/opensearchapi/api_script-painless_execute.go new file mode 100644 index 000000000..60d833d19 --- /dev/null +++ b/opensearchapi/api_script-painless_execute.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ScriptPainlessExecuteReq represents possible options for the delete script request +type ScriptPainlessExecuteReq struct { + Body io.Reader + + Header http.Header + Params ScriptPainlessExecuteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptPainlessExecuteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_scripts/painless/_execute", + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ScriptPainlessExecuteResp represents the returned struct of the delete script response +type ScriptPainlessExecuteResp struct { + Result json.RawMessage `json:"result"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptPainlessExecuteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_script-put-params.go b/opensearchapi/api_script-put-params.go new file mode 100644 index 000000000..abebbaefc --- /dev/null +++ b/opensearchapi/api_script-put-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// ScriptPutParams represents possible parameters for the ScriptPutReq +type ScriptPutParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ScriptPutParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_script-put.go b/opensearchapi/api_script-put.go new file mode 100644 index 000000000..3b5bacf3a --- /dev/null +++ b/opensearchapi/api_script-put.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ScriptPutReq represents possible options for the put script request +type ScriptPutReq struct { + ScriptID string + ScriptContext string + + Body io.Reader + + Header http.Header + Params ScriptPutParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScriptPutReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("/_scripts//") + len(r.ScriptID) + len(r.ScriptContext)) + path.WriteString("/_scripts/") + path.WriteString(r.ScriptID) + if r.ScriptContext != "" { + path.WriteString("/") + path.WriteString(r.ScriptContext) + } + + return opensearch.BuildRequest( + "PUT", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ScriptPutResp represents the returned struct of the put script response +type ScriptPutResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScriptPutResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_script.go b/opensearchapi/api_script.go new file mode 100644 index 000000000..2e3e0b60f --- /dev/null +++ b/opensearchapi/api_script.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type scriptClient struct { + apiClient *Client +} + +// Delete executes a delete script request with the required ScriptDeleteReq +func (c scriptClient) Delete(ctx context.Context, req ScriptDeleteReq) (*ScriptDeleteResp, error) { + var ( + data ScriptDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Put executes an put script request with the required ScriptPutReq +func (c scriptClient) Put(ctx context.Context, req ScriptPutReq) (*ScriptPutResp, error) { + var ( + data ScriptPutResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a /_script request with the required ScriptGetReq +func (c scriptClient) Get(ctx context.Context, req ScriptGetReq) (*ScriptGetResp, error) { + var ( + data ScriptGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Context executes a /_script_context request with the optional ScriptContextReq +func (c scriptClient) Context(ctx context.Context, req *ScriptContextReq) (*ScriptContextResp, error) { + if req == nil { + req = &ScriptContextReq{} + } + + var ( + data ScriptContextResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Language executes a /_script_context request with the optional ScriptLanguageReq +func (c scriptClient) Language(ctx context.Context, req *ScriptLanguageReq) (*ScriptLanguageResp, error) { + if req == nil { + req = &ScriptLanguageReq{} + } + + var ( + data ScriptLanguageResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// PainlessExecute executes a /_script request with the required ScriptPainlessExecuteReq +func (c scriptClient) PainlessExecute(ctx context.Context, req ScriptPainlessExecuteReq) (*ScriptPainlessExecuteResp, error) { + var ( + data ScriptPainlessExecuteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_script_test.go b/opensearchapi/api_script_test.go new file mode 100644 index 000000000..7f5785cc4 --- /dev/null +++ b/opensearchapi/api_script_test.go @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestScriptClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + scriptID := "test-script" + + type scriptTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []scriptTests + }{ + { + Name: "Put", + Tests: []scriptTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Script.Put( + nil, + opensearchapi.ScriptPutReq{ + ScriptID: scriptID, + Body: strings.NewReader(`{"script":{"lang":"painless","source":"\n int total = 0;\n for (int i = 0; i < doc['ratings'].length; ++i) {\n total += doc['ratings'][i];\n }\n return total;\n "}}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Script.Put(nil, opensearchapi.ScriptPutReq{ScriptID: scriptID}) + }, + }, + }, + }, + { + Name: "Get", + Tests: []scriptTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Script.Get(nil, opensearchapi.ScriptGetReq{ScriptID: scriptID}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Script.Get(nil, opensearchapi.ScriptGetReq{ScriptID: scriptID}) + }, + }, + }, + }, + { + Name: "Delete", + Tests: []scriptTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Script.Delete(nil, opensearchapi.ScriptDeleteReq{ScriptID: scriptID}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Script.Delete(nil, opensearchapi.ScriptDeleteReq{ScriptID: scriptID}) + }, + }, + }, + }, + { + Name: "Context", + Tests: []scriptTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Script.Context(nil, nil) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Script.Context(nil, nil) + }, + }, + }, + }, + { + Name: "Language", + Tests: []scriptTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Script.Language(nil, nil) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Script.Language(nil, nil) + }, + }, + }, + }, + { + Name: "PainlessExecute", + Tests: []scriptTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Script.PainlessExecute( + nil, + opensearchapi.ScriptPainlessExecuteReq{Body: strings.NewReader(`{"script":{"source":"(params.x + params.y)/ 2","params":{"x":80,"y":100}}}`)}, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Script.PainlessExecute( + nil, + opensearchapi.ScriptPainlessExecuteReq{Body: strings.NewReader(`{"script":{"source":"(params.x + params.y)/ 2","params":{"x":80,"y":100}}}`)}, + ) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + if strings.Contains(value.Name, "Language") { + osapitest.SkipIfBelowVersion(t, client, 2, 3, value.Name) + } + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + } + }) + } + }) + } + + t.Run("ValidateResponse", func(t *testing.T) { + t.Run("Put", func(t *testing.T) { + resp, err := client.Script.Put( + nil, + opensearchapi.ScriptPutReq{ + ScriptID: scriptID, + Body: strings.NewReader(`{"script":{"lang":"painless","source":"\n int total = 0;\n for (int i = 0; i < doc['ratings'].length; ++i) {\n total += doc['ratings'][i];\n }\n return total;\n "}}`), + }, + ) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Get", func(t *testing.T) { + resp, err := client.Script.Get(nil, opensearchapi.ScriptGetReq{ScriptID: scriptID}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Delete", func(t *testing.T) { + resp, err := client.Script.Delete(nil, opensearchapi.ScriptDeleteReq{ScriptID: scriptID}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Context", func(t *testing.T) { + resp, err := client.Script.Context(nil, nil) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("Language", func(t *testing.T) { + osapitest.SkipIfBelowVersion(t, client, 2, 3, "Language") + resp, err := client.Script.Language(nil, nil) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + t.Run("PainlessExecute", func(t *testing.T) { + resp, err := client.Script.PainlessExecute( + nil, + opensearchapi.ScriptPainlessExecuteReq{Body: strings.NewReader(`{"script":{"source":"(params.x + params.y)/ 2","params":{"x":80,"y":100}}}`)}, + ) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + }) +} diff --git a/opensearchapi/api_scroll-delete-params.go b/opensearchapi/api_scroll-delete-params.go new file mode 100644 index 000000000..573d39d95 --- /dev/null +++ b/opensearchapi/api_scroll-delete-params.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +// ScrollDeleteParams represents possible parameters for the ScrollDeleteReq +type ScrollDeleteParams struct { + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ScrollDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_scroll-delete.go b/opensearchapi/api_scroll-delete.go new file mode 100644 index 000000000..c5216fafd --- /dev/null +++ b/opensearchapi/api_scroll-delete.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ScrollDeleteReq represents possible options for the index create request +type ScrollDeleteReq struct { + ScrollIDs []string + + Body io.Reader + + Header http.Header + Params ScrollDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScrollDeleteReq) GetRequest() (*http.Request, error) { + scrolls := strings.Join(r.ScrollIDs, ",") + var path strings.Builder + path.Grow(len("/_search/scroll/") + len(scrolls)) + path.WriteString("/_search/scroll") + if len(r.ScrollIDs) > 0 { + path.WriteString("/") + path.WriteString(scrolls) + } + return opensearch.BuildRequest( + "DELETE", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// ScrollDeleteResp represents the returned struct of the index create response +type ScrollDeleteResp struct { + NumFreed int `json:"num_freed"` + Succeeded bool `json:"succeeded"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScrollDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_scroll-get-params.go b/opensearchapi/api_scroll-get-params.go new file mode 100644 index 000000000..003b44922 --- /dev/null +++ b/opensearchapi/api_scroll-get-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// ScrollGetParams represents possible parameters for the ScrollGetReq +type ScrollGetParams struct { + RestTotalHitsAsInt *bool + Scroll time.Duration + ScrollID string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r ScrollGetParams) get() map[string]string { + params := make(map[string]string) + + if r.RestTotalHitsAsInt != nil { + params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.ScrollID != "" { + params["scroll_id"] = r.ScrollID + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_scroll-get.go b/opensearchapi/api_scroll-get.go new file mode 100644 index 000000000..412fa3194 --- /dev/null +++ b/opensearchapi/api_scroll-get.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// ScrollGetReq represents possible options for the index create request +type ScrollGetReq struct { + ScrollID string + + Header http.Header + Params ScrollGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r ScrollGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + "/_search/scroll", + strings.NewReader(fmt.Sprintf(`{"scroll_id":"%s"}`, r.ScrollID)), + r.Params.get(), + r.Header, + ) +} + +// ScrollGetResp represents the returned struct of the index create response +type ScrollGetResp struct { + Took int `json:"took"` + Timeout bool `json:"timed_out"` + Shards ResponseShards `json:"_shards"` + Hits struct { + Total struct { + Value int `json:"value"` + Relation string `json:"relation"` + } `json:"total"` + MaxScore float32 `json:"max_score"` + Hits []SearchHit `json:"hits"` + } `json:"hits"` + ScrollID *string `json:"_scroll_id,omitempty"` + TerminatedEarly bool `json:"terminated_early"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r ScrollGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_scroll.go b/opensearchapi/api_scroll.go new file mode 100644 index 000000000..f8c4ef17c --- /dev/null +++ b/opensearchapi/api_scroll.go @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type scrollClient struct { + apiClient *Client +} + +// Delete executes a delete scroll request with the required ScrollDeleteReq +func (c scrollClient) Delete(ctx context.Context, req ScrollDeleteReq) (*ScrollDeleteResp, error) { + var ( + data ScrollDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get scroll request with the required ScrollGetReq +func (c scrollClient) Get(ctx context.Context, req ScrollGetReq) (*ScrollGetResp, error) { + var ( + data ScrollGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_scroll_test.go b/opensearchapi/api_scroll_test.go new file mode 100644 index 000000000..aca7e8da6 --- /dev/null +++ b/opensearchapi/api_scroll_test.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestScrollClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + search, err := client.Search( + nil, + &opensearchapi.SearchReq{ + Indices: []string{"test*"}, + Params: opensearchapi.SearchParams{Scroll: 5 * time.Minute}, + }, + ) + require.Nil(t, err) + require.NotNil(t, search.ScrollID) + + type scrollTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []scrollTests + }{ + { + Name: "Get", + Tests: []scrollTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Scroll.Get(nil, opensearchapi.ScrollGetReq{ScrollID: *search.ScrollID}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Scroll.Get(nil, opensearchapi.ScrollGetReq{}) + }, + }, + }, + }, + { + Name: "Delete", + Tests: []scrollTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Scroll.Delete(nil, opensearchapi.ScrollDeleteReq{ScrollIDs: []string{"_all"}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Scroll.Delete(nil, opensearchapi.ScrollDeleteReq{}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + }) + } + }) + } +} diff --git a/opensearchapi/api_search-params.go b/opensearchapi/api_search-params.go new file mode 100644 index 000000000..3dcff95f0 --- /dev/null +++ b/opensearchapi/api_search-params.go @@ -0,0 +1,284 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// SearchParams represents possible parameters for the SearchReq +type SearchParams struct { + AllowNoIndices *bool + AllowPartialSearchResults *bool + Analyzer string + AnalyzeWildcard *bool + BatchedReduceSize *int + CcsMinimizeRoundtrips *bool + DefaultOperator string + Df string + DocvalueFields []string + ExpandWildcards string + Explain *bool + From *int + IgnoreThrottled *bool + IgnoreUnavailable *bool + Lenient *bool + MaxConcurrentShardRequests *int + MinCompatibleShardNode string + Preference string + PreFilterShardSize *int + Query string + RequestCache *bool + RestTotalHitsAsInt *bool + Routing []string + Scroll time.Duration + SearchType string + SeqNoPrimaryTerm *bool + Size *int + Sort []string + Source interface{} + SourceExcludes []string + SourceIncludes []string + Stats []string + StoredFields []string + SuggestField string + SuggestMode string + SuggestSize *int + SuggestText string + TerminateAfter *int + Timeout time.Duration + TrackScores *bool + TrackTotalHits interface{} + TypedKeys *bool + Version *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SearchParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.AllowPartialSearchResults != nil { + params["allow_partial_search_results"] = strconv.FormatBool(*r.AllowPartialSearchResults) + } + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.BatchedReduceSize != nil { + params["batched_reduce_size"] = strconv.FormatInt(int64(*r.BatchedReduceSize), 10) + } + + if r.CcsMinimizeRoundtrips != nil { + params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if len(r.DocvalueFields) > 0 { + params["docvalue_fields"] = strings.Join(r.DocvalueFields, ",") + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Explain != nil { + params["explain"] = strconv.FormatBool(*r.Explain) + } + + if r.From != nil { + params["from"] = strconv.FormatInt(int64(*r.From), 10) + } + + if r.IgnoreThrottled != nil { + params["ignore_throttled"] = strconv.FormatBool(*r.IgnoreThrottled) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.MaxConcurrentShardRequests != nil { + params["max_concurrent_shard_requests"] = strconv.FormatInt(int64(*r.MaxConcurrentShardRequests), 10) + } + + if r.MinCompatibleShardNode != "" { + params["min_compatible_shard_node"] = r.MinCompatibleShardNode + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.PreFilterShardSize != nil { + params["pre_filter_shard_size"] = strconv.FormatInt(int64(*r.PreFilterShardSize), 10) + } + + if r.Query != "" { + params["q"] = r.Query + } + + if r.RequestCache != nil { + params["request_cache"] = strconv.FormatBool(*r.RequestCache) + } + + if r.RestTotalHitsAsInt != nil { + params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) + } + + if len(r.Routing) > 0 { + params["routing"] = strings.Join(r.Routing, ",") + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.SeqNoPrimaryTerm != nil { + params["seq_no_primary_term"] = strconv.FormatBool(*r.SeqNoPrimaryTerm) + } + + if r.Size != nil { + params["size"] = strconv.FormatInt(int64(*r.Size), 10) + } + + if len(r.Sort) > 0 { + params["sort"] = strings.Join(r.Sort, ",") + } + + switch source := r.Source.(type) { + case bool: + params["_source"] = strconv.FormatBool(source) + case string: + if source != "" { + params["_source"] = source + } + case []string: + if len(source) > 0 { + params["_source"] = strings.Join(source, ",") + } + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.Stats) > 0 { + params["stats"] = strings.Join(r.Stats, ",") + } + + if len(r.StoredFields) > 0 { + params["stored_fields"] = strings.Join(r.StoredFields, ",") + } + + if r.SuggestField != "" { + params["suggest_field"] = r.SuggestField + } + + if r.SuggestMode != "" { + params["suggest_mode"] = r.SuggestMode + } + + if r.SuggestSize != nil { + params["suggest_size"] = strconv.FormatInt(int64(*r.SuggestSize), 10) + } + + if r.SuggestText != "" { + params["suggest_text"] = r.SuggestText + } + + if r.TerminateAfter != nil { + params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.TrackScores != nil { + params["track_scores"] = strconv.FormatBool(*r.TrackScores) + } + + if r.TrackTotalHits != nil { + params["track_total_hits"] = fmt.Sprintf("%v", r.TrackTotalHits) + } + + if r.TypedKeys != nil { + params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) + } + + if r.Version != nil { + params["version"] = strconv.FormatBool(*r.Version) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_search-template-params.go b/opensearchapi/api_search-template-params.go new file mode 100644 index 000000000..6e28be0c8 --- /dev/null +++ b/opensearchapi/api_search-template-params.go @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// SearchTemplateParams represents possible parameters for the SearchTemplateReq +type SearchTemplateParams struct { + AllowNoIndices *bool + CcsMinimizeRoundtrips *bool + ExpandWildcards string + Explain *bool + IgnoreThrottled *bool + IgnoreUnavailable *bool + Preference string + Profile *bool + RestTotalHitsAsInt *bool + Routing []string + Scroll time.Duration + SearchType string + TypedKeys *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SearchTemplateParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.CcsMinimizeRoundtrips != nil { + params["ccs_minimize_roundtrips"] = strconv.FormatBool(*r.CcsMinimizeRoundtrips) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.Explain != nil { + params["explain"] = strconv.FormatBool(*r.Explain) + } + + if r.IgnoreThrottled != nil { + params["ignore_throttled"] = strconv.FormatBool(*r.IgnoreThrottled) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Profile != nil { + params["profile"] = strconv.FormatBool(*r.Profile) + } + + if r.RestTotalHitsAsInt != nil { + params["rest_total_hits_as_int"] = strconv.FormatBool(*r.RestTotalHitsAsInt) + } + + if len(r.Routing) > 0 { + params["routing"] = strings.Join(r.Routing, ",") + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.TypedKeys != nil { + params["typed_keys"] = strconv.FormatBool(*r.TypedKeys) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_search-template.go b/opensearchapi/api_search-template.go new file mode 100644 index 000000000..479f3457f --- /dev/null +++ b/opensearchapi/api_search-template.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SearchTemplate executes a /_search request with the optional SearchTemplateReq +func (c Client) SearchTemplate(ctx context.Context, req SearchTemplateReq) (*SearchTemplateResp, error) { + var ( + data SearchTemplateResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// SearchTemplateReq represents possible options for the /_search request +type SearchTemplateReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params SearchTemplateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SearchTemplateReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("//_search/template") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_search/template") + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SearchTemplateResp represents the returned struct of the /_search response +type SearchTemplateResp struct { + Took int `json:"took"` + Timeout bool `json:"timed_out"` + Shards ResponseShards `json:"_shards"` + Hits struct { + Total struct { + Value int `json:"value"` + Relation string `json:"relation"` + } `json:"total"` + MaxScore *float32 `json:"max_score"` + Hits []SearchHit `json:"hits"` + } `json:"hits"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SearchTemplateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_search-template_test.go b/opensearchapi/api_search-template_test.go new file mode 100644 index 000000000..ed9691a96 --- /dev/null +++ b/opensearchapi/api_search-template_test.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestSearchTemplate(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testIndex := "test-search-template" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + }) + + for i := 1; i <= 2; i++ { + _, err = client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{"foo": "bar"}`), + DocumentID: strconv.Itoa(i), + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + } + + t.Run("with request", func(t *testing.T) { + resp, err := client.SearchTemplate( + nil, + opensearchapi.SearchTemplateReq{ + Indices: []string{testIndex}, + Body: strings.NewReader(`{"source":{"query":{"exists":{"field":"{{field}}"}}},"params":{"field":"foo"}}`), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.SearchTemplate(nil, opensearchapi.SearchTemplateReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_search.go b/opensearchapi/api_search.go new file mode 100644 index 000000000..c765fa6cf --- /dev/null +++ b/opensearchapi/api_search.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// Search executes a /_search request with the optional SearchReq +func (c Client) Search(ctx context.Context, req *SearchReq) (*SearchResp, error) { + if req == nil { + req = &SearchReq{} + } + + var ( + data SearchResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// SearchReq represents possible options for the /_search request +type SearchReq struct { + Indices []string + Body io.Reader + + Header http.Header + Params SearchParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SearchReq) GetRequest() (*http.Request, error) { + var path string + if len(r.Indices) > 0 { + path = fmt.Sprintf("/%s/_search", strings.Join(r.Indices, ",")) + } else { + path = "_search" + } + + return opensearch.BuildRequest( + "POST", + path, + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SearchResp represents the returned struct of the /_search response +type SearchResp struct { + Took int `json:"took"` + Timeout bool `json:"timed_out"` + Shards ResponseShards `json:"_shards"` + Hits struct { + Total struct { + Value int `json:"value"` + Relation string `json:"relation"` + } `json:"total"` + MaxScore float32 `json:"max_score"` + Hits []SearchHit `json:"hits"` + } `json:"hits"` + Errors bool `json:"errors"` + Aggregations json.RawMessage `json:"aggregations"` + ScrollID *string `json:"_scroll_id,omitempty"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SearchResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// SearchHit is a sub type of SearchResp containing information of the search hit with an unparsed Source field +type SearchHit struct { + Index string `json:"_index"` + ID string `json:"_id"` + Score float32 `json:"_score"` + Source json.RawMessage `json:"_source"` + Type string `json:"_type"` // Deprecated field + Sort []any `json:"sort"` +} diff --git a/opensearchapi/api_search_shards-params.go b/opensearchapi/api_search_shards-params.go new file mode 100644 index 000000000..c63ecadac --- /dev/null +++ b/opensearchapi/api_search_shards-params.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" +) + +// SearchShardsParams represents possible parameters for the SearchShardsReq +type SearchShardsParams struct { + AllowNoIndices *bool + ExpandWildcards string + IgnoreUnavailable *bool + Local *bool + Preference string + Routing string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SearchShardsParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_search_shards.go b/opensearchapi/api_search_shards.go new file mode 100644 index 000000000..a0e59dbd9 --- /dev/null +++ b/opensearchapi/api_search_shards.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SearchShards executes a /_search request with the optional SearchShardsReq +func (c Client) SearchShards(ctx context.Context, req *SearchShardsReq) (*SearchShardsResp, error) { + if req == nil { + req = &SearchShardsReq{} + } + + var ( + data SearchShardsResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// SearchShardsReq represents possible options for the /_search request +type SearchShardsReq struct { + Indices []string + + Header http.Header + Params SearchShardsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SearchShardsReq) GetRequest() (*http.Request, error) { + indices := strings.Join(r.Indices, ",") + var path strings.Builder + path.Grow(len("//_search_shards") + len(indices)) + if len(r.Indices) > 0 { + path.WriteString("/") + path.WriteString(indices) + } + path.WriteString("/_search_shards") + + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// SearchShardsResp represents the returned struct of the /_search response +type SearchShardsResp struct { + Nodes map[string]struct { + Name string `json:"name"` + EphemeralID string `json:"ephemeral_id"` + TransportAddress string `json:"transport_address"` + Attributes map[string]string `json:"attributes"` + } `json:"nodes"` + Indices map[string]json.RawMessage `json:"indices"` + Shards [][]struct { + State string `json:"state"` + Primary bool `json:"primary"` + Node string `json:"node"` + RelocatingNode *string `json:"relocating_node"` + Shard int `json:"shard"` + Index string `json:"index"` + ExpectedShardSizeInBytes int `json:"expected_shard_size_in_bytes"` + RecoverySource struct { + Type string `json:"type"` + } `json:"recovery_source"` + UnassignedInfo struct { + Reason string `json:"reason"` + At string `json:"at"` + Delayed bool `json:"delayed"` + AllocationStatus string `json:"allocation_status"` + } `json:"unassigned_info"` + AllocationID struct { + ID string `json:"id"` + } `json:"allocation_id"` + } `json:"shards"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SearchShardsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_search_shards_test.go b/opensearchapi/api_search_shards_test.go new file mode 100644 index 000000000..d1a08f7fd --- /dev/null +++ b/opensearchapi/api_search_shards_test.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "testing" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSearchShards(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + index := "test-index-search-shards" + + _, err = client.Indices.Create( + nil, + opensearchapi.IndicesCreateReq{ + Index: index, + }, + ) + require.Nil(t, err) + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{index}}) + }) + + t.Run("with nil request", func(t *testing.T) { + resp, err := client.SearchShards(nil, nil) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("with request", func(t *testing.T) { + resp, err := client.SearchShards(nil, &opensearchapi.SearchShardsReq{Indices: []string{index}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.SearchShards(nil, nil) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_search_test.go b/opensearchapi/api_search_test.go new file mode 100644 index 000000000..9f92eb2be --- /dev/null +++ b/opensearchapi/api_search_test.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSearch(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + index := "test-index-search" + + _, err = client.Index( + nil, + opensearchapi.IndexReq{ + Index: index, + Body: strings.NewReader(`{"foo": "bar"}`), + Params: opensearchapi.IndexParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{index}}) + }) + + t.Run("with nil request", func(t *testing.T) { + resp, err := client.Search(nil, nil) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + assert.NotEmpty(t, resp.Hits.Hits) + }) + + t.Run("with request", func(t *testing.T) { + resp, err := client.Search(nil, &opensearchapi.SearchReq{Indices: []string{index}, Body: strings.NewReader("")}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + assert.NotEmpty(t, resp.Hits.Hits) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.Search(nil, nil) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_snapshot-clone-params.go b/opensearchapi/api_snapshot-clone-params.go new file mode 100644 index 000000000..3e67f9bb2 --- /dev/null +++ b/opensearchapi/api_snapshot-clone-params.go @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// SnapshotCloneParams represents possible parameters for the SnapshotCloneReq +type SnapshotCloneParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotCloneParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot-clone.go b/opensearchapi/api_snapshot-clone.go new file mode 100644 index 000000000..12456852b --- /dev/null +++ b/opensearchapi/api_snapshot-clone.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotCloneReq represents possible options for the index create request +type SnapshotCloneReq struct { + Repo string + Snapshot string + TargetSnapshot string + + Body io.Reader + + Header http.Header + Params SnapshotCloneParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotCloneReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_snapshot/%s/%s/_clone/%s", r.Repo, r.Snapshot, r.TargetSnapshot), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SnapshotCloneResp represents the returned struct of the index create response +type SnapshotCloneResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotCloneResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_snapshot-create-params.go b/opensearchapi/api_snapshot-create-params.go new file mode 100644 index 000000000..9ae6386c0 --- /dev/null +++ b/opensearchapi/api_snapshot-create-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// SnapshotCreateParams represents possible parameters for the SnapshotCreateReq +type SnapshotCreateParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotCreateParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot-create.go b/opensearchapi/api_snapshot-create.go new file mode 100644 index 000000000..f6121f29f --- /dev/null +++ b/opensearchapi/api_snapshot-create.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotCreateReq represents possible options for the index create request +type SnapshotCreateReq struct { + Repo string + Snapshot string + + Body io.Reader + + Header http.Header + Params SnapshotCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_snapshot/%s/%s", r.Repo, r.Snapshot), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SnapshotCreateResp represents the returned struct of the index create response +type SnapshotCreateResp struct { + Accepted bool `json:"accepted"` + Snapshot struct { + Snapshot string `json:"snapshot"` + UUID string `json:"uuid"` + VersionID int `json:"version_id"` + Version string `json:"version"` + RemoteStoreIndexShallowCopy bool `json:"remote_store_index_shallow_copy"` + Indices []string `json:"indices"` + DataStreams []json.RawMessage `json:"data_streams"` + IncludeGlobalState bool `json:"include_global_state"` + Metadata map[string]string `json:"metadata"` + State string `json:"state"` + StartTime string `json:"start_time"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + EndTime string `json:"end_time"` + EndTimeInMillis int64 `json:"end_time_in_millis"` + DurationInMillis int `json:"duration_in_millis"` + Failures []json.RawMessage `json:"failures"` + Shards struct { + Total int `json:"total"` + Failed int `json:"failed"` + Successful int `json:"successful"` + } `json:"shards"` + } `json:"snapshot"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_snapshot-delete-params.go b/opensearchapi/api_snapshot-delete-params.go new file mode 100644 index 000000000..93fdecebb --- /dev/null +++ b/opensearchapi/api_snapshot-delete-params.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// SnapshotDeleteParams represents possible parameters for the SnapshotDeleteReq +type SnapshotDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot-delete.go b/opensearchapi/api_snapshot-delete.go new file mode 100644 index 000000000..2a73fb5aa --- /dev/null +++ b/opensearchapi/api_snapshot-delete.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotDeleteReq represents possible options for the index create request +type SnapshotDeleteReq struct { + Repo string + Snapshots []string + + Header http.Header + Params SnapshotDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_snapshot/%s/%s", r.Repo, strings.Join(r.Snapshots, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotDeleteResp represents the returned struct of the index create response +type SnapshotDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_snapshot-get-params.go b/opensearchapi/api_snapshot-get-params.go new file mode 100644 index 000000000..9a2205dbc --- /dev/null +++ b/opensearchapi/api_snapshot-get-params.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// SnapshotGetParams represents possible parameters for the SnapshotGetReq +type SnapshotGetParams struct { + IgnoreUnavailable *bool + IncludeRepository *bool + IndexDetails *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Verbose *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotGetParams) get() map[string]string { + params := make(map[string]string) + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.IncludeRepository != nil { + params["include_repository"] = strconv.FormatBool(*r.IncludeRepository) + } + + if r.IndexDetails != nil { + params["index_details"] = strconv.FormatBool(*r.IndexDetails) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Verbose != nil { + params["verbose"] = strconv.FormatBool(*r.Verbose) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot-get.go b/opensearchapi/api_snapshot-get.go new file mode 100644 index 000000000..06c321f61 --- /dev/null +++ b/opensearchapi/api_snapshot-get.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotGetReq represents possible options for the index create request +type SnapshotGetReq struct { + Repo string + Snapshots []string + + Body io.Reader + + Header http.Header + Params SnapshotGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_snapshot/%s/%s", r.Repo, strings.Join(r.Snapshots, ",")), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SnapshotGetResp represents the returned struct of the index create response +type SnapshotGetResp struct { + Snapshots []struct { + Snapshot string `json:"snapshot"` + UUID string `json:"uuid"` + VersionID int `json:"version_id"` + Version string `json:"version"` + RemoteStoreIndexShallowCopy bool `json:"remote_store_index_shallow_copy"` + Indices []string `json:"indices"` + DataStreams []json.RawMessage `json:"data_streams"` + IncludeGlobalState bool `json:"include_global_state"` + Metadata map[string]string `json:"metadata"` + State string `json:"state"` + StartTime string `json:"start_time"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + EndTime string `json:"end_time"` + EndTimeInMillis int64 `json:"end_time_in_millis"` + DurationInMillis int `json:"duration_in_millis"` + Failures []json.RawMessage `json:"failures"` + Shards struct { + Total int `json:"total"` + Failed int `json:"failed"` + Successful int `json:"successful"` + } `json:"shards"` + } `json:"snapshots"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_snapshot-restore-params.go b/opensearchapi/api_snapshot-restore-params.go new file mode 100644 index 000000000..b03ae1a16 --- /dev/null +++ b/opensearchapi/api_snapshot-restore-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// SnapshotRestoreParams represents possible parameters for the SnapshotRestoreReq +type SnapshotRestoreParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotRestoreParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot-restore.go b/opensearchapi/api_snapshot-restore.go new file mode 100644 index 000000000..cee208043 --- /dev/null +++ b/opensearchapi/api_snapshot-restore.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotRestoreReq represents possible options for the index create request +type SnapshotRestoreReq struct { + Repo string + Snapshot string + + Body io.Reader + + Header http.Header + Params SnapshotRestoreParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRestoreReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_snapshot/%s/%s/_restore", r.Repo, r.Snapshot), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRestoreResp represents the returned struct of the index create response +type SnapshotRestoreResp struct { + Accepted bool `json:"accepted"` + Snapshot struct { + Snapshot string `json:"snapshot"` + Indices []string `json:"indices"` + Shards struct { + Total int `json:"total"` + Failed int `json:"failed"` + Successful int `json:"successful"` + } `json:"shards"` + } `json:"snapshot"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRestoreResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_snapshot-status-params.go b/opensearchapi/api_snapshot-status-params.go new file mode 100644 index 000000000..bf5457c52 --- /dev/null +++ b/opensearchapi/api_snapshot-status-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// SnapshotStatusParams represents possible parameters for the SnapshotStatusReq +type SnapshotStatusParams struct { + IgnoreUnavailable *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotStatusParams) get() map[string]string { + params := make(map[string]string) + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot-status.go b/opensearchapi/api_snapshot-status.go new file mode 100644 index 000000000..9cfc686db --- /dev/null +++ b/opensearchapi/api_snapshot-status.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotStatusReq represents possible options for the index create request +type SnapshotStatusReq struct { + Repo string + Snapshots []string + + Header http.Header + Params SnapshotStatusParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotStatusReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_snapshot/%s/%s/_status", r.Repo, strings.Join(r.Snapshots, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotStatusResp represents the returned struct of the index create response +type SnapshotStatusResp struct { + Accepted bool `json:"accepted"` + Snapshots []struct { + Snapshot string `json:"snapshot"` + Repository string `json:"repository"` + UUID string `json:"uuid"` + State string `json:"state"` + IncludeGlobalState bool `json:"include_global_state"` + ShardsStats SnapshotStatusShardsStats `json:"shards_stats"` + Stats SnapshotStatusStats `json:"stats"` + Indices map[string]struct { + ShardsStats SnapshotStatusShardsStats `json:"shards_stats"` + Stats SnapshotStatusStats `json:"stats"` + Shards map[string]struct { + Stage string `json:"stage"` + Stats SnapshotStatusStats `json:"stats"` + } `json:"shards"` + } `json:"indices"` + } `json:"snapshots"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotStatusResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// SnapshotStatusShardsStats is a sub type of SnapshotStatusResp containing information about shard stats +type SnapshotStatusShardsStats struct { + Initializing int `json:"initializing"` + Started int `json:"started"` + Finalizing int `json:"finalizing"` + Done int `json:"done"` + Failed int `json:"failed"` + Total int `json:"total"` +} + +// SnapshotStatusStats is a sub type of SnapshotStatusResp containing information about snapshot stats +type SnapshotStatusStats struct { + Incremental struct { + FileCount int `json:"file_count"` + SizeInBytes int64 `json:"size_in_bytes"` + } `json:"incremental"` + Total struct { + FileCount int `json:"file_count"` + SizeInBytes int64 `json:"size_in_bytes"` + } `json:"total"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + TimeInMillis int `json:"time_in_millis"` +} diff --git a/opensearchapi/api_snapshot.go b/opensearchapi/api_snapshot.go new file mode 100644 index 000000000..9fa754828 --- /dev/null +++ b/opensearchapi/api_snapshot.go @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import "context" + +type snapshotClient struct { + apiClient *Client + Repository repositoryClient +} + +// Create executes a creade snapshot request with the required SnapshotCreateReq +func (c snapshotClient) Create(ctx context.Context, req SnapshotCreateReq) (*SnapshotCreateResp, error) { + var ( + data SnapshotCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete snapshot request with the required SnapshotDeleteReq +func (c snapshotClient) Delete(ctx context.Context, req SnapshotDeleteReq) (*SnapshotDeleteResp, error) { + var ( + data SnapshotDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get snapshot request with the required SnapshotGetReq +func (c snapshotClient) Get(ctx context.Context, req SnapshotGetReq) (*SnapshotGetResp, error) { + var ( + data SnapshotGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Clone executes a snapshot clone request with the required SnapshotCloneReq +func (c snapshotClient) Clone(ctx context.Context, req SnapshotCloneReq) (*SnapshotCloneResp, error) { + var ( + data SnapshotCloneResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Restore executes a snapshot restore request with the required SnapshotRestoreReq +func (c snapshotClient) Restore(ctx context.Context, req SnapshotRestoreReq) (*SnapshotRestoreResp, error) { + var ( + data SnapshotRestoreResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Status executes a snapshot status request with the required SnapshotStatusReq +func (c snapshotClient) Status(ctx context.Context, req SnapshotStatusReq) (*SnapshotStatusResp, error) { + var ( + data SnapshotStatusResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_snapshot_repository-cleanup-params.go b/opensearchapi/api_snapshot_repository-cleanup-params.go new file mode 100644 index 000000000..9b3b8ea7f --- /dev/null +++ b/opensearchapi/api_snapshot_repository-cleanup-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// SnapshotRepositoryCleanupParams represents possible parameters for the SnapshotRepositoryCleanupReq +type SnapshotRepositoryCleanupParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotRepositoryCleanupParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot_repository-cleanup.go b/opensearchapi/api_snapshot_repository-cleanup.go new file mode 100644 index 000000000..eb03f79ad --- /dev/null +++ b/opensearchapi/api_snapshot_repository-cleanup.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotRepositoryCleanupReq represents possible options for the index create request +type SnapshotRepositoryCleanupReq struct { + Repo string + + Header http.Header + Params SnapshotRepositoryCleanupParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRepositoryCleanupReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_snapshot/%s/_cleanup", r.Repo), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRepositoryCleanupResp represents the returned struct of the index create response +type SnapshotRepositoryCleanupResp struct { + Results struct { + DeletedBytes int `json:"deleted_bytes"` + DeletedBlobs int `json:"deleted_blobs"` + } `json:"results"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRepositoryCleanupResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_snapshot_repository-create-params.go b/opensearchapi/api_snapshot_repository-create-params.go new file mode 100644 index 000000000..b9945f4c9 --- /dev/null +++ b/opensearchapi/api_snapshot_repository-create-params.go @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// SnapshotRepositoryCreateParams represents possible parameters for the SnapshotRepositoryCreateReq +type SnapshotRepositoryCreateParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + Verify *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotRepositoryCreateParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Verify != nil { + params["verify"] = strconv.FormatBool(*r.Verify) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot_repository-create.go b/opensearchapi/api_snapshot_repository-create.go new file mode 100644 index 000000000..cd77c7ad0 --- /dev/null +++ b/opensearchapi/api_snapshot_repository-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotRepositoryCreateReq represents possible options for the index create request +type SnapshotRepositoryCreateReq struct { + Repo string + + Body io.Reader + + Header http.Header + Params SnapshotRepositoryCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRepositoryCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_snapshot/%s", r.Repo), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRepositoryCreateResp represents the returned struct of the index create response +type SnapshotRepositoryCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRepositoryCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_snapshot_repository-delete-params.go b/opensearchapi/api_snapshot_repository-delete-params.go new file mode 100644 index 000000000..ed821942a --- /dev/null +++ b/opensearchapi/api_snapshot_repository-delete-params.go @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// SnapshotRepositoryDeleteParams represents possible parameters for the SnapshotRepositoryDeleteReq +type SnapshotRepositoryDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotRepositoryDeleteParams) get() map[string]string { + params := make(map[string]string) + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot_repository-delete.go b/opensearchapi/api_snapshot_repository-delete.go new file mode 100644 index 000000000..f418d7363 --- /dev/null +++ b/opensearchapi/api_snapshot_repository-delete.go @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotRepositoryDeleteReq represents possible options for the index create request +type SnapshotRepositoryDeleteReq struct { + Repos []string + + Header http.Header + Params SnapshotRepositoryDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRepositoryDeleteReq) GetRequest() (*http.Request, error) { + repos := strings.Join(r.Repos, ",") + + var path strings.Builder + path.Grow(len("/_snapshot/") + len(repos)) + path.WriteString("/_snapshot") + if len(r.Repos) > 0 { + path.WriteString("/") + path.WriteString(repos) + } + + return opensearch.BuildRequest( + "DELETE", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRepositoryDeleteResp represents the returned struct of the index create response +type SnapshotRepositoryDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRepositoryDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_snapshot_repository-get-params.go b/opensearchapi/api_snapshot_repository-get-params.go new file mode 100644 index 000000000..a1865e39f --- /dev/null +++ b/opensearchapi/api_snapshot_repository-get-params.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// SnapshotRepositoryGetParams represents possible parameters for the SnapshotRepositoryGetReq +type SnapshotRepositoryGetParams struct { + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotRepositoryGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot_repository-get.go b/opensearchapi/api_snapshot_repository-get.go new file mode 100644 index 000000000..b68f67a16 --- /dev/null +++ b/opensearchapi/api_snapshot_repository-get.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotRepositoryGetReq represents possible options for the index create request +type SnapshotRepositoryGetReq struct { + Repos []string + + Header http.Header + Params SnapshotRepositoryGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRepositoryGetReq) GetRequest() (*http.Request, error) { + repos := strings.Join(r.Repos, ",") + + var path strings.Builder + path.Grow(len("/_snapshot/") + len(repos)) + path.WriteString("/_snapshot") + if len(r.Repos) > 0 { + path.WriteString("/") + path.WriteString(repos) + } + + return opensearch.BuildRequest( + "GET", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRepositoryGetResp represents the returned struct of the index create response +type SnapshotRepositoryGetResp struct { + Repos map[string]struct { + Type string `json:"type"` + Settings map[string]string `json:"settings"` + } + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRepositoryGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_snapshot_repository-verify-params.go b/opensearchapi/api_snapshot_repository-verify-params.go new file mode 100644 index 000000000..e6a9d1956 --- /dev/null +++ b/opensearchapi/api_snapshot_repository-verify-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// SnapshotRepositoryVerifyParams represents possible parameters for the SnapshotRepositoryVerifyReq +type SnapshotRepositoryVerifyParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r SnapshotRepositoryVerifyParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_snapshot_repository-verify.go b/opensearchapi/api_snapshot_repository-verify.go new file mode 100644 index 000000000..b5a76b681 --- /dev/null +++ b/opensearchapi/api_snapshot_repository-verify.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// SnapshotRepositoryVerifyReq represents possible options for the index create request +type SnapshotRepositoryVerifyReq struct { + Repo string + + Header http.Header + Params SnapshotRepositoryVerifyParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r SnapshotRepositoryVerifyReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_snapshot/%s/_verify", r.Repo), + nil, + r.Params.get(), + r.Header, + ) +} + +// SnapshotRepositoryVerifyResp represents the returned struct of the index create response +type SnapshotRepositoryVerifyResp struct { + Nodes map[string]struct { + Name string `json:"name"` + } `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r SnapshotRepositoryVerifyResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_snapshot_repository.go b/opensearchapi/api_snapshot_repository.go new file mode 100644 index 000000000..9bd139a9c --- /dev/null +++ b/opensearchapi/api_snapshot_repository.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type repositoryClient struct { + apiClient *Client +} + +// Create executes a put repository request with the required SnapshotRepositoryCreateReq +func (c repositoryClient) Create(ctx context.Context, req SnapshotRepositoryCreateReq) (*SnapshotRepositoryCreateResp, error) { + var ( + data SnapshotRepositoryCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete repository request with the required SnapshotRepositoryDeleteReq +func (c repositoryClient) Delete(ctx context.Context, req SnapshotRepositoryDeleteReq) (*SnapshotRepositoryDeleteResp, error) { + var ( + data SnapshotRepositoryDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get repository request with the optional SnapshotRepositoryGetReq +func (c repositoryClient) Get(ctx context.Context, req *SnapshotRepositoryGetReq) (*SnapshotRepositoryGetResp, error) { + if req == nil { + req = &SnapshotRepositoryGetReq{} + } + var ( + data SnapshotRepositoryGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Repos); err != nil { + return &data, err + } + + return &data, nil +} + +// Cleanup executes a cleanup repository request with the required SnapshotRepositoryCleanupReq +func (c repositoryClient) Cleanup(ctx context.Context, req SnapshotRepositoryCleanupReq) (*SnapshotRepositoryCleanupResp, error) { + var ( + data SnapshotRepositoryCleanupResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Verify executes a verify repository request with the required SnapshotRepositoryVerifyReq +func (c repositoryClient) Verify(ctx context.Context, req SnapshotRepositoryVerifyReq) (*SnapshotRepositoryVerifyResp, error) { + var ( + data SnapshotRepositoryVerifyResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_snapshot_test.go b/opensearchapi/api_snapshot_test.go new file mode 100644 index 000000000..65cad3a02 --- /dev/null +++ b/opensearchapi/api_snapshot_test.go @@ -0,0 +1,318 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "fmt" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestSnapshotClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + testRepo := "test-repository" + testSnapshot := "test-snapshot" + testCloneSnapshot := "test-snapshot-clone" + testIndex := "test-snapshot" + + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + }) + + for i := 1; i <= 2; i++ { + _, err = client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{"foo": "bar"}`), + DocumentID: strconv.Itoa(i), + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + } + + type snapshotTests struct { + Name string + Results func() (osapitest.Response, error) + } + testCases := []struct { + Name string + Tests []snapshotTests + }{ + { + Name: "Repository Create", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Snapshot.Repository.Create( + nil, + opensearchapi.SnapshotRepositoryCreateReq{ + Repo: testRepo, + Body: strings.NewReader(`{"type":"fs","settings":{"location":"/usr/share/opensearch/mnt"}}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Repository.Create(nil, opensearchapi.SnapshotRepositoryCreateReq{}) + }, + }, + }, + }, + { + Name: "Repository Get", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Snapshot.Repository.Get(nil, &opensearchapi.SnapshotRepositoryGetReq{Repos: []string{testRepo}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Repository.Get(nil, nil) + }, + }, + }, + }, + { + Name: "Repository Cleanup", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Snapshot.Repository.Cleanup(nil, opensearchapi.SnapshotRepositoryCleanupReq{Repo: testRepo}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Repository.Cleanup(nil, opensearchapi.SnapshotRepositoryCleanupReq{}) + }, + }, + }, + }, + { + Name: "Repository Verify", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Snapshot.Repository.Verify(nil, opensearchapi.SnapshotRepositoryVerifyReq{Repo: testRepo}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Repository.Verify(nil, opensearchapi.SnapshotRepositoryVerifyReq{}) + }, + }, + }, + }, + { + Name: "Create", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Snapshot.Create( + nil, + opensearchapi.SnapshotCreateReq{ + Repo: testRepo, + Snapshot: testSnapshot, + Body: strings.NewReader(fmt.Sprintf(`{"indices":"%s"}`, testIndex)), + Params: opensearchapi.SnapshotCreateParams{WaitForCompletion: opensearchapi.ToPointer(true)}, + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Create(nil, opensearchapi.SnapshotCreateReq{}) + }, + }, + }, + }, + { + Name: "Clone", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Snapshot.Clone( + nil, + opensearchapi.SnapshotCloneReq{ + Repo: testRepo, + Snapshot: testSnapshot, + TargetSnapshot: testCloneSnapshot, + Body: strings.NewReader(fmt.Sprintf(`{"indices":"%s"}`, testIndex)), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Clone(nil, opensearchapi.SnapshotCloneReq{}) + }, + }, + }, + }, + { + Name: "Get", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Snapshot.Get(nil, opensearchapi.SnapshotGetReq{Repo: testRepo, Snapshots: []string{testSnapshot, testCloneSnapshot}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Get(nil, opensearchapi.SnapshotGetReq{}) + }, + }, + }, + }, + { + Name: "Restore", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + return client.Snapshot.Restore( + nil, + opensearchapi.SnapshotRestoreReq{ + Repo: testRepo, + Snapshot: testSnapshot, + Params: opensearchapi.SnapshotRestoreParams{WaitForCompletion: opensearchapi.ToPointer(true)}, + }) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Restore(nil, opensearchapi.SnapshotRestoreReq{}) + }, + }, + }, + }, + { + Name: "Status", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Snapshot.Status(nil, opensearchapi.SnapshotStatusReq{Repo: testRepo, Snapshots: []string{testSnapshot, testCloneSnapshot}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Status(nil, opensearchapi.SnapshotStatusReq{}) + }, + }, + }, + }, + { + Name: "Delete", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Snapshot.Delete(nil, opensearchapi.SnapshotDeleteReq{Repo: testRepo, Snapshots: []string{testSnapshot, testCloneSnapshot}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Delete(nil, opensearchapi.SnapshotDeleteReq{}) + }, + }, + }, + }, + { + Name: "Repository Delete", + Tests: []snapshotTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Snapshot.Repository.Delete(nil, opensearchapi.SnapshotRepositoryDeleteReq{Repos: []string{testRepo}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Snapshot.Repository.Delete(nil, opensearchapi.SnapshotRepositoryDeleteReq{}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + if value.Name != "Repository Get" { + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + } + }) + } + }) + } + t.Run("ValidateResponse", func(t *testing.T) { + _, err := client.Snapshot.Repository.Create( + nil, + opensearchapi.SnapshotRepositoryCreateReq{ + Repo: testRepo, + Body: strings.NewReader(`{"type":"fs","settings":{"location":"/usr/share/opensearch/mnt"}}`), + }, + ) + require.Nil(t, err) + t.Cleanup(func() { + client.Snapshot.Repository.Delete(nil, opensearchapi.SnapshotRepositoryDeleteReq{Repos: []string{testRepo}}) + }) + + t.Run("Repository Get", func(t *testing.T) { + resp, err := client.Snapshot.Repository.Get(nil, &opensearchapi.SnapshotRepositoryGetReq{Repos: []string{testRepo}}) + require.Nil(t, err) + assert.NotNil(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Repos, resp.Inspect().Response) + }) + }) +} diff --git a/internal/build/cmd/generate/commands/gensource/generator_test.go b/opensearchapi/api_tasks-cancel-params.go similarity index 55% rename from internal/build/cmd/generate/commands/gensource/generator_test.go rename to opensearchapi/api_tasks-cancel-params.go index 62181e197..c113649ab 100644 --- a/internal/build/cmd/generate/commands/gensource/generator_test.go +++ b/opensearchapi/api_tasks-cancel-params.go @@ -24,44 +24,55 @@ // specific language governing permissions and limitations // under the License. -package gensource_test +package opensearchapi import ( - "io/ioutil" - "os" + "strconv" "strings" - "testing" - - "github.com/opensearch-project/opensearch-go/v2/internal/build/cmd/generate/commands/gensource" ) -func TestGenerator(t *testing.T) { - t.Run("Output", func(t *testing.T) { - f, err := os.Open("testdata/info.json") - if err != nil { - t.Fatalf("Error: %s", err) - } +// TasksCancelParams represents possible parameters for the TasksCancelReq +type TasksCancelParams struct { + Actions []string + Nodes []string + ParentTaskID string + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r TasksCancelParams) get() map[string]string { + params := make(map[string]string) + + if len(r.Actions) > 0 { + params["actions"] = strings.Join(r.Actions, ",") + } + + if len(r.Nodes) > 0 { + params["nodes"] = strings.Join(r.Nodes, ",") + } + + if r.ParentTaskID != "" { + params["parent_task_id"] = r.ParentTaskID + } - endpoint, err := gensource.NewEndpoint(f) - if err != nil { - t.Fatalf("Error creating endpoint for %q: %s", f.Name(), err) - } + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } - gen := gensource.Generator{Endpoint: endpoint} + if r.Pretty { + params["pretty"] = "true" + } - out, err := gen.OutputFormatted() - if err != nil { - t.Fatalf("Error generating output for %q: %s", f.Name(), err) - } + if r.Human { + params["human"] = "true" + } - s, err := ioutil.ReadAll(out) - if err != nil { - t.Fatalf("Error reading output for %q: %s", f.Name(), err) - } - // t.Logf("\n%s\n", s) + if r.ErrorTrace { + params["error_trace"] = "true" + } - if !strings.Contains(string(s), "func newInfoFunc(t Transport) Info {") { - t.Error("Incorrect output") - } - }) + return params } diff --git a/opensearchapi/api_tasks-cancel.go b/opensearchapi/api_tasks-cancel.go new file mode 100644 index 000000000..df1084681 --- /dev/null +++ b/opensearchapi/api_tasks-cancel.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// TasksCancelReq represents possible options for the index create request +type TasksCancelReq struct { + TaskID string + + Header http.Header + Params TasksCancelParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TasksCancelReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("/_tasks//_cancel") + len(r.TaskID)) + path.WriteString("/_tasks") + if r.TaskID != "" { + path.WriteString("/") + path.WriteString(r.TaskID) + } + path.WriteString("/_cancel") + return opensearch.BuildRequest( + "POST", + path.String(), + nil, + r.Params.get(), + r.Header, + ) +} + +// TasksCancelResp represents the returned struct of the index create response +type TasksCancelResp struct { + Nodes map[string]TaskCancel `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TasksCancelResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// TaskCancel is a sub type of TaskCancelResp containing information about a node the task was running on +type TaskCancel struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Tasks map[string]TaskCancelInfo `json:"tasks"` +} + +// TaskCancelInfo is a sub type of TaskCancle containing information about the canceled task +type TaskCancelInfo struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int `json:"running_time_in_nanos"` + CancellationTimeMillis int64 `json:"cancellation_time_millis"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers json.RawMessage `json:"headers"` +} diff --git a/opensearchapi/api_tasks-get-params.go b/opensearchapi/api_tasks-get-params.go new file mode 100644 index 000000000..d420928d1 --- /dev/null +++ b/opensearchapi/api_tasks-get-params.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// TasksGetParams represents possible parameters for the TasksGetReq +type TasksGetParams struct { + Timeout time.Duration + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r TasksGetParams) get() map[string]string { + params := make(map[string]string) + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_tasks-get.go b/opensearchapi/api_tasks-get.go new file mode 100644 index 000000000..ed1973130 --- /dev/null +++ b/opensearchapi/api_tasks-get.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// TasksGetReq represents possible options for the index create request +type TasksGetReq struct { + TaskID string + + Header http.Header + Params TasksGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TasksGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_tasks/%s", r.TaskID), + nil, + r.Params.get(), + r.Header, + ) +} + +// TasksGetResp represents the returned struct of the index create response +type TasksGetResp struct { + Completed bool `json:"completed"` + Task struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + Description string `json:"description"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int64 `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers json.RawMessage `json:"headers"` + ResourceStats struct { + Average struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"average"` + Total struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"total"` + Min struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"min"` + Max struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"max"` + ThreadInfo struct { + ThreadExecutions int `json:"thread_executions"` + ActiveThreads int `json:"active_threads"` + } `json:"thread_info"` + } `json:"resource_stats"` + } `json:"task"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TasksGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// TasksGetDetails is a sub type of TasksGetResp containing information about an index template +type TasksGetDetails struct { + Order int64 `json:"order"` + Version int64 `json:"version"` + IndexPatterns []string `json:"index_patterns"` + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` +} diff --git a/opensearchapi/api_tasks-list-params.go b/opensearchapi/api_tasks-list-params.go new file mode 100644 index 000000000..f0dfd6c03 --- /dev/null +++ b/opensearchapi/api_tasks-list-params.go @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// TasksListParams represents possible parameters for the TasksListReq +type TasksListParams struct { + Actions []string + Detailed *bool + GroupBy string + Nodes []string + ParentTaskID string + Timeout time.Duration + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r TasksListParams) get() map[string]string { + params := make(map[string]string) + + if len(r.Actions) > 0 { + params["actions"] = strings.Join(r.Actions, ",") + } + + if r.Detailed != nil { + params["detailed"] = strconv.FormatBool(*r.Detailed) + } + + if r.GroupBy != "" { + params["group_by"] = r.GroupBy + } + + if len(r.Nodes) > 0 { + params["nodes"] = strings.Join(r.Nodes, ",") + } + + if r.ParentTaskID != "" { + params["parent_task_id"] = r.ParentTaskID + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_tasks-list.go b/opensearchapi/api_tasks-list.go new file mode 100644 index 000000000..bf4b19f81 --- /dev/null +++ b/opensearchapi/api_tasks-list.go @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// TasksListReq represents possible options for the index create request +type TasksListReq struct { + Header http.Header + Params TasksListParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TasksListReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + "/_tasks", + nil, + r.Params.get(), + r.Header, + ) +} + +// TasksListResp represents the returned struct of the index create response +type TasksListResp struct { + Nodes map[string]TasksListNodes `json:"nodes"` + Tasks map[string]TasksListTask `json:"tasks"` // tasks is returned when group_by is set to none or parents + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TasksListResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// TasksListNodes is a sub type of TaskListResp containing information about a node and the tasks running on it +type TasksListNodes struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Tasks map[string]TasksListTask `json:"tasks"` +} + +// TasksListTask is a sub type of TaskListResp, TaskListNodes containing information about a task +type TasksListTask struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + Description string `json:"description"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int64 `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers map[string]string `json:"headers"` + ResourceStats TasksListResourceStats `json:"resource_stats"` + ParentTaskID string `json:"parent_task_id"` + Children []TasksListTask `json:"children,omitempty"` +} + +// TasksListResourceStats is a sub type of TaskListTask containing information about task stats +type TasksListResourceStats struct { + Average struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"average"` + Total struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"total"` + Min struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"min"` + Max struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"max"` + ThreadInfo struct { + ThreadExecutions int `json:"thread_executions"` + ActiveThreads int `json:"active_threads"` + } `json:"thread_info"` +} diff --git a/opensearchapi/api_tasks.go b/opensearchapi/api_tasks.go new file mode 100644 index 000000000..bd31696f9 --- /dev/null +++ b/opensearchapi/api_tasks.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" +) + +type tasksClient struct { + apiClient *Client +} + +// Cancel executes a delete tasks request with the required TasksCancelReq +func (c tasksClient) Cancel(ctx context.Context, req TasksCancelReq) (*TasksCancelResp, error) { + var ( + data TasksCancelResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// List executes a get tasks request with the optional TasksListReq +func (c tasksClient) List(ctx context.Context, req *TasksListReq) (*TasksListResp, error) { + if req == nil { + req = &TasksListReq{} + } + + var ( + data TasksListResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get tasks request with the optional TasksGetReq +func (c tasksClient) Get(ctx context.Context, req TasksGetReq) (*TasksGetResp, error) { + var ( + data TasksGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} diff --git a/opensearchapi/api_tasks_test.go b/opensearchapi/api_tasks_test.go new file mode 100644 index 000000000..2c0d2f9de --- /dev/null +++ b/opensearchapi/api_tasks_test.go @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "context" + "fmt" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" + "github.com/opensearch-project/opensearch-go/v2/opensearchutil" +) + +func TestTasksClient(t *testing.T) { + t.Parallel() + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + sourceIndex := "test-tasks-source" + destIndex := "test-tasks-dest" + testIndices := []string{sourceIndex, destIndex} + t.Cleanup(func() { + client.Indices.Delete( + nil, + opensearchapi.IndicesDeleteReq{ + Indices: testIndices, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + }) + + ctx := context.Background() + for _, index := range testIndices { + client.Indices.Create( + ctx, + opensearchapi.IndicesCreateReq{ + Index: index, + Body: strings.NewReader(`{"settings": {"number_of_shards": 1, "number_of_replicas": 0}}`), + Params: opensearchapi.IndicesCreateParams{WaitForActiveShards: "1"}, + }, + ) + } + bi, err := opensearchutil.NewBulkIndexer(opensearchutil.BulkIndexerConfig{ + Index: sourceIndex, + Client: client, + Refresh: "wait_for", + }) + for i := 1; i <= 60; i++ { + err := bi.Add(ctx, opensearchutil.BulkIndexerItem{ + Action: "index", + DocumentID: strconv.Itoa(i), + Body: strings.NewReader(`{"title":"bar"}`), + }) + if err != nil { + t.Fatalf("Unexpected error: %s", err) + } + } + if err := bi.Close(ctx); err != nil { + t.Errorf("Unexpected error: %s", err) + } + + respReindex, err := client.Reindex( + ctx, + opensearchapi.ReindexReq{ + Body: strings.NewReader(fmt.Sprintf(`{"source":{"index":"%s","size":1},"dest":{"index":"%s"}}`, sourceIndex, destIndex)), + Params: opensearchapi.ReindexParams{ + WaitForCompletion: opensearchapi.ToPointer(false), + RequestsPerSecond: opensearchapi.ToPointer(1), + Refresh: opensearchapi.ToPointer(true), + }, + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, respReindex) + + type tasksTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []tasksTests + }{ + { + Name: "List", + Tests: []tasksTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Tasks.List(nil, nil) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Tasks.List(nil, nil) + }, + }, + }, + }, + { + Name: "Get", + Tests: []tasksTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Tasks.Get(nil, opensearchapi.TasksGetReq{TaskID: respReindex.Task}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Tasks.Get(nil, opensearchapi.TasksGetReq{}) + }, + }, + }, + }, + { + Name: "Cancel", + Tests: []tasksTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Tasks.Cancel(nil, opensearchapi.TasksCancelReq{TaskID: respReindex.Task}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Tasks.Cancel(nil, opensearchapi.TasksCancelReq{}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + if value.Name != "Get" && value.Name != "Exists" { + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + } + }) + } + }) + } +} diff --git a/opensearchapi/api_template-create-params.go b/opensearchapi/api_template-create-params.go new file mode 100644 index 000000000..c9f063838 --- /dev/null +++ b/opensearchapi/api_template-create-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// TemplateCreateParams represents possible parameters for the TemplateCreateReq +type TemplateCreateParams struct { + Create *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Order *int + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r TemplateCreateParams) get() map[string]string { + params := make(map[string]string) + + if r.Create != nil { + params["create"] = strconv.FormatBool(*r.Create) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Order != nil { + params["order"] = strconv.FormatInt(int64(*r.Order), 10) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_template-create.go b/opensearchapi/api_template-create.go new file mode 100644 index 000000000..96ecc6311 --- /dev/null +++ b/opensearchapi/api_template-create.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// TemplateCreateReq represents possible options for the index create request +type TemplateCreateReq struct { + Template string + + Body io.Reader + + Header http.Header + Params TemplateCreateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TemplateCreateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "PUT", + fmt.Sprintf("/_template/%s", r.Template), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// TemplateCreateResp represents the returned struct of the index create response +type TemplateCreateResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TemplateCreateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_template-delete-params.go b/opensearchapi/api_template-delete-params.go new file mode 100644 index 000000000..72a899e27 --- /dev/null +++ b/opensearchapi/api_template-delete-params.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "time" +) + +// TemplateDeleteParams represents possible parameters for the TemplateDeleteReq +type TemplateDeleteParams struct { + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + Timeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r TemplateDeleteParams) get() map[string]string { + params := make(map[string]string) + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_template-delete.go b/opensearchapi/api_template-delete.go new file mode 100644 index 000000000..efb707964 --- /dev/null +++ b/opensearchapi/api_template-delete.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// TemplateDeleteReq represents possible options for the index create request +type TemplateDeleteReq struct { + Template string + + Header http.Header + Params TemplateDeleteParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TemplateDeleteReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "DELETE", + fmt.Sprintf("/_template/%s", r.Template), + nil, + r.Params.get(), + r.Header, + ) +} + +// TemplateDeleteResp represents the returned struct of the index create response +type TemplateDeleteResp struct { + Acknowledged bool `json:"acknowledged"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TemplateDeleteResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_template-exists-params.go b/opensearchapi/api_template-exists-params.go new file mode 100644 index 000000000..00d566b21 --- /dev/null +++ b/opensearchapi/api_template-exists-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// TemplateExistsParams represents possible parameters for the TemplateExistsReq +type TemplateExistsParams struct { + FlatSettings *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r TemplateExistsParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_template-exists.go b/opensearchapi/api_template-exists.go new file mode 100644 index 000000000..da95bb949 --- /dev/null +++ b/opensearchapi/api_template-exists.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// TemplateExistsReq represents possible options for the index create request +type TemplateExistsReq struct { + Template string + + Header http.Header + Params TemplateExistsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TemplateExistsReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "HEAD", + fmt.Sprintf("/_template/%s", r.Template), + nil, + r.Params.get(), + r.Header, + ) +} diff --git a/opensearchapi/api_template-get-params.go b/opensearchapi/api_template-get-params.go new file mode 100644 index 000000000..ec30a245f --- /dev/null +++ b/opensearchapi/api_template-get-params.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "time" +) + +// TemplateGetParams represents possible parameters for the TemplateGetReq +type TemplateGetParams struct { + FlatSettings *bool + Local *bool + MasterTimeout time.Duration + ClusterManagerTimeout time.Duration + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r TemplateGetParams) get() map[string]string { + params := make(map[string]string) + + if r.FlatSettings != nil { + params["flat_settings"] = strconv.FormatBool(*r.FlatSettings) + } + + if r.Local != nil { + params["local"] = strconv.FormatBool(*r.Local) + } + + if r.MasterTimeout != 0 { + params["master_timeout"] = formatDuration(r.MasterTimeout) + } + + if r.ClusterManagerTimeout != 0 { + params["cluster_manager_timeout"] = formatDuration(r.ClusterManagerTimeout) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_template-get.go b/opensearchapi/api_template-get.go new file mode 100644 index 000000000..38a0ff283 --- /dev/null +++ b/opensearchapi/api_template-get.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// TemplateGetReq represents possible options for the index create request +type TemplateGetReq struct { + Templates []string + + Header http.Header + Params TemplateGetParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TemplateGetReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "GET", + fmt.Sprintf("/_template/%s", strings.Join(r.Templates, ",")), + nil, + r.Params.get(), + r.Header, + ) +} + +// TemplateGetResp represents the returned struct of the index create response +type TemplateGetResp struct { + Templates map[string]TemplateGetDetails + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TemplateGetResp) Inspect() Inspect { + return Inspect{Response: r.response} +} + +// TemplateGetDetails is a sub type of TemplateGetResp containing information about an index template +type TemplateGetDetails struct { + Order int64 `json:"order"` + Version int64 `json:"version"` + IndexPatterns []string `json:"index_patterns"` + Mappings json.RawMessage `json:"mappings"` + Settings json.RawMessage `json:"settings"` + Aliases json.RawMessage `json:"aliases"` +} diff --git a/opensearchapi/api_template.go b/opensearchapi/api_template.go new file mode 100644 index 000000000..218b4137b --- /dev/null +++ b/opensearchapi/api_template.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + + "github.com/opensearch-project/opensearch-go/v2" +) + +type templateClient struct { + apiClient *Client +} + +// Create executes a creade template request with the required TemplateCreateReq +// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndexTemplate.Create instread +func (c templateClient) Create(ctx context.Context, req TemplateCreateReq) (*TemplateCreateResp, error) { + var ( + data TemplateCreateResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Delete executes a delete template request with the required TemplateDeleteReq +// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndexTemplate.Delete instread +func (c templateClient) Delete(ctx context.Context, req TemplateDeleteReq) (*TemplateDeleteResp, error) { + var ( + data TemplateDeleteResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// Get executes a get template request with the optional TemplateGetReq +// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndexTemplate.Get instread +func (c templateClient) Get(ctx context.Context, req *TemplateGetReq) (*TemplateGetResp, error) { + if req == nil { + req = &TemplateGetReq{} + } + + var ( + data TemplateGetResp + err error + ) + if data.response, err = c.apiClient.do(ctx, req, &data.Templates); err != nil { + return &data, err + } + + return &data, nil +} + +// Exists executes a exists template request with the required TemplatExistsReq +// Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndexTemplate.Exists instread +func (c templateClient) Exists(ctx context.Context, req TemplateExistsReq) (*opensearch.Response, error) { + return c.apiClient.do(ctx, req, nil) +} diff --git a/opensearchapi/api_template_test.go b/opensearchapi/api_template_test.go new file mode 100644 index 000000000..be0511963 --- /dev/null +++ b/opensearchapi/api_template_test.go @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestTemplateClient(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + template := "index-template-test" + + type templateTests struct { + Name string + Results func() (osapitest.Response, error) + } + + testCases := []struct { + Name string + Tests []templateTests + }{ + { + Name: "Create", + Tests: []templateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Template.Create( + nil, + opensearchapi.TemplateCreateReq{ + Template: template, + Body: strings.NewReader(`{"order":1,"index_patterns":["index-template-test"],"aliases":{"test-1234":{}},"version":1}`), + }, + ) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Template.Create(nil, opensearchapi.TemplateCreateReq{Template: template}) + }, + }, + }, + }, + { + Name: "Get", + Tests: []templateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Template.Get(nil, &opensearchapi.TemplateGetReq{Templates: []string{template}}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Template.Get(nil, nil) + }, + }, + }, + }, + { + Name: "Exists", + Tests: []templateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = client.Template.Exists(nil, opensearchapi.TemplateExistsReq{Template: template}) + return resp, err + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + var ( + resp dummyInspect + err error + ) + resp.response, err = failingClient.Template.Exists(nil, opensearchapi.TemplateExistsReq{Template: template}) + return resp, err + }, + }, + }, + }, + { + Name: "Delete", + Tests: []templateTests{ + { + Name: "with request", + Results: func() (osapitest.Response, error) { + return client.Template.Delete(nil, opensearchapi.TemplateDeleteReq{Template: template}) + }, + }, + { + Name: "inspect", + Results: func() (osapitest.Response, error) { + return failingClient.Template.Delete(nil, opensearchapi.TemplateDeleteReq{Template: template}) + }, + }, + }, + }, + } + for _, value := range testCases { + t.Run(value.Name, func(t *testing.T) { + for _, testCase := range value.Tests { + t.Run(testCase.Name, func(t *testing.T) { + res, err := testCase.Results() + if testCase.Name == "inspect" { + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + } else { + require.Nil(t, err) + require.NotNil(t, res) + assert.NotNil(t, res.Inspect().Response) + if value.Name != "Get" && value.Name != "Exists" { + osapitest.CompareRawJSONwithParsedJSON(t, res, res.Inspect().Response) + } + } + }) + } + }) + } + t.Run("ValidateResponse", func(t *testing.T) { + t.Run("Get", func(t *testing.T) { + _, err := client.Template.Create( + nil, + opensearchapi.TemplateCreateReq{ + Template: template, + Body: strings.NewReader(`{"order":1,"index_patterns":["index-template-test"],"aliases":{"test-1234":{}},"version":1}`), + }, + ) + require.Nil(t, err) + resp, err := client.Template.Get(nil, &opensearchapi.TemplateGetReq{Templates: []string{template}}) + require.Nil(t, err) + require.NotNil(t, resp) + require.NotNil(t, resp.Inspect().Response) + osapitest.CompareRawJSONwithParsedJSON(t, resp.Templates, resp.Inspect().Response) + }) + }) +} diff --git a/opensearchapi/api_termvectors-params.go b/opensearchapi/api_termvectors-params.go new file mode 100644 index 000000000..2a253b64e --- /dev/null +++ b/opensearchapi/api_termvectors-params.go @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" +) + +// TermvectorsParams represents possible parameters for the TermvectorsReq +type TermvectorsParams struct { + Fields []string + FieldStatistics *bool + Offsets *bool + Payloads *bool + Positions *bool + Preference string + Realtime *bool + Routing string + TermStatistics *bool + Version *int + VersionType string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r TermvectorsParams) get() map[string]string { + params := make(map[string]string) + + if len(r.Fields) > 0 { + params["fields"] = strings.Join(r.Fields, ",") + } + + if r.FieldStatistics != nil { + params["field_statistics"] = strconv.FormatBool(*r.FieldStatistics) + } + + if r.Offsets != nil { + params["offsets"] = strconv.FormatBool(*r.Offsets) + } + + if r.Payloads != nil { + params["payloads"] = strconv.FormatBool(*r.Payloads) + } + + if r.Positions != nil { + params["positions"] = strconv.FormatBool(*r.Positions) + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Realtime != nil { + params["realtime"] = strconv.FormatBool(*r.Realtime) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if r.TermStatistics != nil { + params["term_statistics"] = strconv.FormatBool(*r.TermStatistics) + } + + if r.Version != nil { + params["version"] = strconv.FormatInt(int64(*r.Version), 10) + } + + if r.VersionType != "" { + params["version_type"] = r.VersionType + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_termvectors.go b/opensearchapi/api_termvectors.go new file mode 100644 index 000000000..7a8be30f7 --- /dev/null +++ b/opensearchapi/api_termvectors.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// Termvectors executes a /_termvectors request with the required TermvectorsReq +func (c Client) Termvectors(ctx context.Context, req TermvectorsReq) (*TermvectorsResp, error) { + var ( + data TermvectorsResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// TermvectorsReq represents possible options for the /_termvectors request +type TermvectorsReq struct { + Index string + DocumentID string + + Body io.Reader + + Header http.Header + Params TermvectorsParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r TermvectorsReq) GetRequest() (*http.Request, error) { + var path strings.Builder + path.Grow(len("//_termvectors/") + len(r.Index) + len(r.DocumentID)) + if len(r.Index) > 0 { + path.WriteString("/") + path.WriteString(r.Index) + } + path.WriteString("/_termvectors") + if len(r.DocumentID) > 0 { + path.WriteString("/") + path.WriteString(r.DocumentID) + } + return opensearch.BuildRequest( + "POST", + path.String(), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// TermvectorsResp represents the returned struct of the /_termvectors response +type TermvectorsResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Found bool `json:"found"` + Took int `json:"took"` + Type string `json:"_type"` // Deprecated field + TermVectors json.RawMessage `json:"term_vectors"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r TermvectorsResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_termvectors_test.go b/opensearchapi/api_termvectors_test.go new file mode 100644 index 000000000..6b5b2b28f --- /dev/null +++ b/opensearchapi/api_termvectors_test.go @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestTermvectors(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testIndex := "test-termvectors" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + }) + + _, err = client.Indices.Create( + nil, + opensearchapi.IndicesCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{ "mappings": { + "properties": { + "text": { + "type": "text", + "term_vector": "with_positions_offsets_payloads", + "store" : true, + "analyzer" : "fulltext_analyzer" + }, + "fullname": { + "type": "text", + "term_vector": "with_positions_offsets_payloads", + "analyzer" : "fulltext_analyzer" + } + } + }, + "settings" : { + "index" : { + "number_of_shards" : 1, + "number_of_replicas" : 0 + }, + "analysis": { + "analyzer": { + "fulltext_analyzer": { + "type": "custom", + "tokenizer": "whitespace", + "filter": [ + "lowercase", + "type_as_payload" + ] + } + } + } + } +}`), + }, + ) + require.Nil(t, err) + docs := []string{`{"fullname":"John Doe","text":"test test test "}`, `{"fullname":"Jane Doe","text":"Another test ..."}`} + for i, doc := range docs { + _, err = client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: testIndex, + Body: strings.NewReader(doc), + DocumentID: strconv.Itoa(i), + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + } + + t.Run("with request", func(t *testing.T) { + resp, err := client.Termvectors( + nil, + opensearchapi.TermvectorsReq{ + Index: testIndex, + DocumentID: "1", + Body: strings.NewReader(`{"fields":["*"],"offsets":true,"payloads":true,"positions":true,"term_statistics":true,"field_statistics":true}`), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.Termvectors(nil, opensearchapi.TermvectorsReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_update-params.go b/opensearchapi/api_update-params.go new file mode 100644 index 000000000..069e93198 --- /dev/null +++ b/opensearchapi/api_update-params.go @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" + "strings" + "time" +) + +// UpdateParams represents possible parameters for the UpdateReq +type UpdateParams struct { + IfPrimaryTerm *int + IfSeqNo *int + Lang string + Refresh string + RequireAlias *bool + RetryOnConflict *int + Routing string + Source interface{} + SourceExcludes []string + SourceIncludes []string + Timeout time.Duration + WaitForActiveShards string + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r UpdateParams) get() map[string]string { + params := make(map[string]string) + + if r.IfPrimaryTerm != nil { + params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10) + } + + if r.IfSeqNo != nil { + params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10) + } + + if r.Lang != "" { + params["lang"] = r.Lang + } + + if r.Refresh != "" { + params["refresh"] = r.Refresh + } + + if r.RequireAlias != nil { + params["require_alias"] = strconv.FormatBool(*r.RequireAlias) + } + + if r.RetryOnConflict != nil { + params["retry_on_conflict"] = strconv.FormatInt(int64(*r.RetryOnConflict), 10) + } + + if r.Routing != "" { + params["routing"] = r.Routing + } + + if source, ok := r.Source.(bool); ok { + params["_source"] = strconv.FormatBool(source) + } else if source, ok := r.Source.(string); ok && source != "" { + params["_source"] = source + } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { + params["_source"] = strings.Join(sources, ",") + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_update.go b/opensearchapi/api_update.go new file mode 100644 index 000000000..672f69159 --- /dev/null +++ b/opensearchapi/api_update.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "fmt" + "io" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// Update executes a /_update request with the optional UpdateReq +func (c Client) Update(ctx context.Context, req UpdateReq) (*UpdateResp, error) { + var ( + data UpdateResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// UpdateReq represents possible options for the /_update request +type UpdateReq struct { + Index string + DocumentID string + + Body io.Reader + + Header http.Header + Params UpdateParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r UpdateReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_update/%s", r.Index, r.DocumentID), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// UpdateResp represents the returned struct of the /_update response +type UpdateResp struct { + Index string `json:"_index"` + ID string `json:"_id"` + Version int `json:"_version"` + Result string `json:"result"` + Shards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + } `json:"_shards"` + SeqNo int `json:"_seq_no"` + PrimaryTerm int `json:"_primary_term"` + Type string `json:"_type"` // Deprecated field + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r UpdateResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_update_by_query-params.go b/opensearchapi/api_update_by_query-params.go new file mode 100644 index 000000000..365bc4bd2 --- /dev/null +++ b/opensearchapi/api_update_by_query-params.go @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// UpdateByQueryParams represents possible parameters for the UpdateByQueryReq +type UpdateByQueryParams struct { + AllowNoIndices *bool + Analyzer string + AnalyzeWildcard *bool + Conflicts string + DefaultOperator string + Df string + ExpandWildcards string + From *int + IgnoreUnavailable *bool + Lenient *bool + MaxDocs *int + Pipeline string + Preference string + Query string + Refresh *bool + RequestCache *bool + RequestsPerSecond *int + Routing []string + Scroll time.Duration + ScrollSize *int + SearchTimeout time.Duration + SearchType string + Size *int + Slices interface{} + Sort []string + Source interface{} + SourceExcludes []string + SourceIncludes []string + Stats []string + TerminateAfter *int + Timeout time.Duration + Version *bool + VersionType *bool + WaitForActiveShards string + WaitForCompletion *bool + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r UpdateByQueryParams) get() map[string]string { + params := make(map[string]string) + + if r.AllowNoIndices != nil { + params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices) + } + + if r.Analyzer != "" { + params["analyzer"] = r.Analyzer + } + + if r.AnalyzeWildcard != nil { + params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard) + } + + if r.Conflicts != "" { + params["conflicts"] = r.Conflicts + } + + if r.DefaultOperator != "" { + params["default_operator"] = r.DefaultOperator + } + + if r.Df != "" { + params["df"] = r.Df + } + + if r.ExpandWildcards != "" { + params["expand_wildcards"] = r.ExpandWildcards + } + + if r.From != nil { + params["from"] = strconv.FormatInt(int64(*r.From), 10) + } + + if r.IgnoreUnavailable != nil { + params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable) + } + + if r.Lenient != nil { + params["lenient"] = strconv.FormatBool(*r.Lenient) + } + + if r.MaxDocs != nil { + params["max_docs"] = strconv.FormatInt(int64(*r.MaxDocs), 10) + } + + if r.Pipeline != "" { + params["pipeline"] = r.Pipeline + } + + if r.Preference != "" { + params["preference"] = r.Preference + } + + if r.Query != "" { + params["q"] = r.Query + } + + if r.Refresh != nil { + params["refresh"] = strconv.FormatBool(*r.Refresh) + } + + if r.RequestCache != nil { + params["request_cache"] = strconv.FormatBool(*r.RequestCache) + } + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if len(r.Routing) > 0 { + params["routing"] = strings.Join(r.Routing, ",") + } + + if r.Scroll != 0 { + params["scroll"] = formatDuration(r.Scroll) + } + + if r.ScrollSize != nil { + params["scroll_size"] = strconv.FormatInt(int64(*r.ScrollSize), 10) + } + + if r.SearchTimeout != 0 { + params["search_timeout"] = formatDuration(r.SearchTimeout) + } + + if r.SearchType != "" { + params["search_type"] = r.SearchType + } + + if r.Size != nil { + params["size"] = strconv.FormatInt(int64(*r.Size), 10) + } + + if r.Slices != nil { + params["slices"] = fmt.Sprintf("%v", r.Slices) + } + + if len(r.Sort) > 0 { + params["sort"] = strings.Join(r.Sort, ",") + } + + if source, ok := r.Source.(bool); ok { + params["_source"] = strconv.FormatBool(source) + } else if source, ok := r.Source.(string); ok && source != "" { + params["_source"] = source + } else if sources, ok := r.Source.([]string); ok && len(sources) > 0 { + params["_source"] = strings.Join(sources, ",") + } + + if len(r.SourceExcludes) > 0 { + params["_source_excludes"] = strings.Join(r.SourceExcludes, ",") + } + + if len(r.SourceIncludes) > 0 { + params["_source_includes"] = strings.Join(r.SourceIncludes, ",") + } + + if len(r.Stats) > 0 { + params["stats"] = strings.Join(r.Stats, ",") + } + + if r.TerminateAfter != nil { + params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10) + } + + if r.Timeout != 0 { + params["timeout"] = formatDuration(r.Timeout) + } + + if r.Version != nil { + params["version"] = strconv.FormatBool(*r.Version) + } + + if r.VersionType != nil { + params["version_type"] = strconv.FormatBool(*r.VersionType) + } + + if r.WaitForActiveShards != "" { + params["wait_for_active_shards"] = r.WaitForActiveShards + } + + if r.WaitForCompletion != nil { + params["wait_for_completion"] = strconv.FormatBool(*r.WaitForCompletion) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_update_by_query.go b/opensearchapi/api_update_by_query.go new file mode 100644 index 000000000..c69c46800 --- /dev/null +++ b/opensearchapi/api_update_by_query.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// UpdateByQuery executes a /_update_by_query request with the optional UpdateByQueryReq +func (c Client) UpdateByQuery(ctx context.Context, req UpdateByQueryReq) (*UpdateByQueryResp, error) { + var ( + data UpdateByQueryResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// UpdateByQueryReq represents possible options for the /_update_by_query request +type UpdateByQueryReq struct { + Indices []string + + Body io.Reader + + Header http.Header + Params UpdateByQueryParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r UpdateByQueryReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/%s/_update_by_query", strings.Join(r.Indices, ",")), + r.Body, + r.Params.get(), + r.Header, + ) +} + +// UpdateByQueryResp represents the returned struct of the /_update_by_query response +type UpdateByQueryResp struct { + Took int `json:"took"` + TimedOut bool `json:"timed_out"` + Total int `json:"total"` + Updated int `json:"updated"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float32 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + Failures []json.RawMessage `json:"failures"` + Type string `json:"_type"` // Deprecated field + Task string `json:"task"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r UpdateByQueryResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_update_by_query_rethrottle-params.go b/opensearchapi/api_update_by_query_rethrottle-params.go new file mode 100644 index 000000000..f7fe047c5 --- /dev/null +++ b/opensearchapi/api_update_by_query_rethrottle-params.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package opensearchapi + +import ( + "strconv" +) + +// UpdateByQueryRethrottleParams represents possible parameters for the UpdateByQueryRethrottleReq +type UpdateByQueryRethrottleParams struct { + RequestsPerSecond *int + + Pretty bool + Human bool + ErrorTrace bool +} + +func (r UpdateByQueryRethrottleParams) get() map[string]string { + params := make(map[string]string) + + if r.RequestsPerSecond != nil { + params["requests_per_second"] = strconv.FormatInt(int64(*r.RequestsPerSecond), 10) + } + + if r.Pretty { + params["pretty"] = "true" + } + + if r.Human { + params["human"] = "true" + } + + if r.ErrorTrace { + params["error_trace"] = "true" + } + + return params +} diff --git a/opensearchapi/api_update_by_query_rethrottle.go b/opensearchapi/api_update_by_query_rethrottle.go new file mode 100644 index 000000000..1072fdc1a --- /dev/null +++ b/opensearchapi/api_update_by_query_rethrottle.go @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/opensearch-project/opensearch-go/v2" +) + +// UpdateByQueryRethrottle executes a / request with the optional UpdateByQueryRethrottleReq +func (c Client) UpdateByQueryRethrottle(ctx context.Context, req UpdateByQueryRethrottleReq) (*UpdateByQueryRethrottleResp, error) { + var ( + data UpdateByQueryRethrottleResp + err error + ) + if data.response, err = c.do(ctx, req, &data); err != nil { + return &data, err + } + + return &data, nil +} + +// UpdateByQueryRethrottleReq represents possible options for the / request +type UpdateByQueryRethrottleReq struct { + TaskID string + + Header http.Header + Params UpdateByQueryRethrottleParams +} + +// GetRequest returns the *http.Request that gets executed by the client +func (r UpdateByQueryRethrottleReq) GetRequest() (*http.Request, error) { + return opensearch.BuildRequest( + "POST", + fmt.Sprintf("/_update_by_query/%s/_rethrottle", r.TaskID), + nil, + r.Params.get(), + r.Header, + ) +} + +// UpdateByQueryRethrottleResp represents the returned struct of the / response +type UpdateByQueryRethrottleResp struct { + Nodes map[string]struct { + Name string `json:"name"` + TransportAddress string `json:"transport_address"` + Host string `json:"host"` + IP string `json:"ip"` + Roles []string `json:"roles"` + Attributes map[string]string `json:"attributes"` + Tasks map[string]struct { + Node string `json:"node"` + ID int `json:"id"` + Type string `json:"type"` + Action string `json:"action"` + Status struct { + Total int `json:"total"` + Updated int `json:"updated"` + Created int `json:"created"` + Deleted int `json:"deleted"` + Batches int `json:"batches"` + VersionConflicts int `json:"version_conflicts"` + Noops int `json:"noops"` + Retries struct { + Bulk int `json:"bulk"` + Search int `json:"search"` + } `json:"retries"` + ThrottledMillis int `json:"throttled_millis"` + RequestsPerSecond float64 `json:"requests_per_second"` + ThrottledUntilMillis int `json:"throttled_until_millis"` + } `json:"status"` + Description string `json:"description"` + StartTimeInMillis int64 `json:"start_time_in_millis"` + RunningTimeInNanos int `json:"running_time_in_nanos"` + Cancellable bool `json:"cancellable"` + Cancelled bool `json:"cancelled"` + Headers json.RawMessage `json:"headers"` + ResourceStats struct { + Average struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"average"` + Total struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"total"` + Min struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"min"` + Max struct { + CPUTimeInNanos int `json:"cpu_time_in_nanos"` + MemoryInBytes int `json:"memory_in_bytes"` + } `json:"max"` + ThreadInfo struct { + ThreadExecutions int `json:"thread_executions"` + ActiveThreads int `json:"active_threads"` + } `json:"thread_info"` + } `json:"resource_stats"` + } `json:"tasks"` + } `json:"nodes"` + response *opensearch.Response +} + +// Inspect returns the Inspect type containing the raw *opensearch.Reponse +func (r UpdateByQueryRethrottleResp) Inspect() Inspect { + return Inspect{Response: r.response} +} diff --git a/opensearchapi/api_update_by_query_rethrottle_test.go b/opensearchapi/api_update_by_query_rethrottle_test.go new file mode 100644 index 000000000..36842cfda --- /dev/null +++ b/opensearchapi/api_update_by_query_rethrottle_test.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "context" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" + "github.com/opensearch-project/opensearch-go/v2/opensearchutil" +) + +func TestUpdateByQueryRethrottle(t *testing.T) { + t.Parallel() + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testIndex := "test-updatebyquery-rethrottle-source" + t.Cleanup(func() { + client.Indices.Delete( + nil, + opensearchapi.IndicesDeleteReq{ + Indices: []string{testIndex}, + Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}, + }, + ) + }) + + client.Indices.Create( + nil, + opensearchapi.IndicesCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{"settings": {"number_of_shards": 1, "number_of_replicas": 0}}`), + }, + ) + bi, err := opensearchutil.NewBulkIndexer(opensearchutil.BulkIndexerConfig{ + Index: testIndex, + Client: client, + Refresh: "wait_for", + }) + for i := 1; i <= 60; i++ { + err := bi.Add(context.Background(), opensearchutil.BulkIndexerItem{ + Action: "index", + DocumentID: strconv.Itoa(i), + Body: strings.NewReader(`{"foo": "bar", "counter": 1}`), + }) + if err != nil { + t.Fatalf("Unexpected error: %s", err) + } + } + if err := bi.Close(context.Background()); err != nil { + t.Errorf("Unexpected error: %s", err) + } + + updatebyquery, err := client.UpdateByQuery( + nil, + opensearchapi.UpdateByQueryReq{ + Indices: []string{testIndex}, + Body: strings.NewReader(`{"script":{"source":"ctx._source.counter += params.count","lang":"painless","params":{"count":4}}}`), + Params: opensearchapi.UpdateByQueryParams{ + WaitForCompletion: opensearchapi.ToPointer(false), + RequestsPerSecond: opensearchapi.ToPointer(1), + }, + }, + ) + require.Nil(t, err) + t.Run("with request", func(t *testing.T) { + resp, err := client.UpdateByQueryRethrottle( + nil, + opensearchapi.UpdateByQueryRethrottleReq{ + TaskID: updatebyquery.Task, + Params: opensearchapi.UpdateByQueryRethrottleParams{RequestsPerSecond: opensearchapi.ToPointer(40)}, + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.UpdateByQueryRethrottle(nil, opensearchapi.UpdateByQueryRethrottleReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_update_by_query_test.go b/opensearchapi/api_update_by_query_test.go new file mode 100644 index 000000000..20a5c9307 --- /dev/null +++ b/opensearchapi/api_update_by_query_test.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestUpdateByQuery(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testIndex := "test-update_by_query" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + }) + + for i := 1; i <= 2; i++ { + _, err = client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{"foo": "bar", "counter": 1}`), + DocumentID: strconv.Itoa(i), + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + } + + t.Run("with request", func(t *testing.T) { + resp, err := client.UpdateByQuery( + nil, + opensearchapi.UpdateByQueryReq{ + Indices: []string{testIndex}, + Body: strings.NewReader(`{"script":{"source":"ctx._source.counter += params.count","lang":"painless","params":{"count":4}}}`), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.UpdateByQuery(nil, opensearchapi.UpdateByQueryReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/api_update_test.go b/opensearchapi/api_update_test.go new file mode 100644 index 000000000..6ac02dc4b --- /dev/null +++ b/opensearchapi/api_update_test.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +//go:build integration + +package opensearchapi_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" + osapitest "github.com/opensearch-project/opensearch-go/v2/opensearchapi/internal/test" +) + +func TestUpdate(t *testing.T) { + client, err := opensearchapi.NewDefaultClient() + require.Nil(t, err) + + testIndex := "test-update" + t.Cleanup(func() { + client.Indices.Delete(nil, opensearchapi.IndicesDeleteReq{Indices: []string{testIndex}}) + }) + + for i := 1; i <= 2; i++ { + _, err = client.Document.Create( + nil, + opensearchapi.DocumentCreateReq{ + Index: testIndex, + Body: strings.NewReader(`{"foo": "bar", "counter": 1}`), + DocumentID: strconv.Itoa(i), + Params: opensearchapi.DocumentCreateParams{Refresh: "true"}, + }, + ) + require.Nil(t, err) + } + + t.Run("with request", func(t *testing.T) { + resp, err := client.Update( + nil, + opensearchapi.UpdateReq{ + Index: testIndex, + DocumentID: "1", + Body: strings.NewReader(`{"script":{"source":"ctx._source.counter += params.count","lang":"painless","params":{"count":4}}}`), + }, + ) + require.Nil(t, err) + assert.NotEmpty(t, resp) + osapitest.CompareRawJSONwithParsedJSON(t, resp, resp.Inspect().Response) + }) + + t.Run("inspect", func(t *testing.T) { + failingClient, err := osapitest.CreateFailingClient() + require.Nil(t, err) + + res, err := failingClient.Update(nil, opensearchapi.UpdateReq{}) + assert.NotNil(t, err) + assert.NotNil(t, res) + osapitest.VerifyInspect(t, res.Inspect()) + }) +} diff --git a/opensearchapi/doc.go b/opensearchapi/doc.go deleted file mode 100644 index 04e8b0a05..000000000 --- a/opensearchapi/doc.go +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -/* -Package opensearchapi provides the Go API for OpenSearch. - -It is automatically included in the client provided by the -github.com/opensearch-project/opensearch-go package: - - client, _ := opensearch.NewDefaultClient() - res, _ := client.Info() - log.Println(res) - -For each OpenSearch API, such as "Index", the package exports two corresponding types: -a function and a struct. - -The function type allows you to call the OpenSearch API as a method on the client, -passing the parameters as arguments: - - res, err := client.Index( - "test", // Index name - strings.NewReader(`{"title" : "Test"}`), // Document body - client.Index.WithDocumentID("1"), // Document ID - client.Index.WithRefresh("true"), // Refresh - ) - if err != nil { - log.Fatalf("ERROR: %s", err) - } - defer res.Body.Close() - - log.Println(res) - - // => [201 Created] {"_index":"test","_type":"_doc","_id":"1" ... - -The struct type allows for a more hands-on approach, where you create a new struct, with the -request configuration as fields, and call the Do() method -with a context and the client as arguments: - - req := opensearchapi.IndexRequest{ - Index: "test", // Index name - Body: strings.NewReader(`{"title" : "Test"}`), // Document body - DocumentID: "1", // Document ID - Refresh: "true", // Refresh - } - - res, err := req.Do(context.Background(), client) - if err != nil { - log.Fatalf("Error getting response: %s", err) - } - defer res.Body.Close() - - log.Println(res) - - // => [200 OK] {"_index":"test","_type":"_doc","_id":"1","_version":2 ... - -The function type is a wrapper around the struct, and allows -to configure and perform the request in a more expressive way. -It has a minor overhead compared to using a struct directly; -refer to the opensearchapi_benchmark_test.go suite for concrete numbers. - -See the documentation for each API function or struct at -https://godoc.org/github.com/opensearch-project/opensearch-go, -or locally by: - - go doc github.com/opensearch-project/opensearch-go/opensearchapi Index - go doc github.com/opensearch-project/opensearch-go/opensearchapi IndexRequest - -Response - -The opensearchapi.Response type is a lightweight wrapper around http.Response. - -The res.Body field is an io.ReadCloser, leaving the JSON parsing to the -calling code, in the interest of performance and flexibility -(eg. to allow using a custom JSON parser). - -It is imperative to close the response body for a non-nil response. - -The Response type implements a couple of convenience methods for accessing -the status, checking an error status code or printing -the response body for debugging purposes. - -*/ -package opensearchapi diff --git a/opensearchapi/error.go b/opensearchapi/error.go new file mode 100644 index 000000000..e08f11cca --- /dev/null +++ b/opensearchapi/error.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import ( + "encoding/json" + "errors" + "fmt" +) + +// Error vars +var ( + ErrUnexpectedEmptyBody = errors.New("body is unexpectedly empty") + ErrReadBody = errors.New("failed to read body") + ErrJSONUnmarshalBody = errors.New("failed to json unmarshal body") + ErrUnknownOpensearchError = errors.New("opensearch error response could not be parsed as error") +) + +// Error represents the Opensearch API error response +type Error struct { + Err Err `json:"error"` + Status int `json:"status"` +} + +// Err represents the error of an API error response +type Err struct { + RootCause []RootCause `json:"root_cause"` + Type string `json:"type"` + Reason string `json:"reason"` + Index string `json:"index,omitempty"` + IndexUUID string `json:"index_uuid,omitempty"` +} + +// RootCause represents the root_cause of an API error response +type RootCause struct { + Type string `json:"type"` + Reason string `json:"reason"` + Index string `json:"index,omitempty"` + IndexUUID string `json:"index_uuid,omitempty"` +} + +// StringError represnets an Opensearch API Error with a string as error +type StringError struct { + Err string `json:"error"` + Status int `json:"status"` +} + +// Error returns a string +func (e Error) Error() string { + return fmt.Sprintf("status: %d, type: %s, reason: %s, root_cause: %s", e.Status, e.Err.Type, e.Err.Reason, e.Err.RootCause) +} + +// Error returns a string +func (e StringError) Error() string { + return fmt.Sprintf("status: %d, error: %s", e.Status, e.Err) +} + +// UnmarshalJSON is a custom unmarshal function for Error returning custom errors in special cases +func (e *Error) UnmarshalJSON(b []byte) error { + var dummy struct { + Err json.RawMessage `json:"error"` + Status int `json:"status"` + } + if err := json.Unmarshal(b, &dummy); err != nil { + return fmt.Errorf("%w: %s", err, b) + } + + if len(dummy.Err) == 0 { + return fmt.Errorf("%w: %s", ErrUnknownOpensearchError, b) + } + + var osErr Err + if err := json.Unmarshal(dummy.Err, &osErr); err != nil { + return StringError{Status: dummy.Status, Err: string(dummy.Err)} + } + if dummy.Status == 0 || (osErr.Type == "" && osErr.Reason == "") { + return fmt.Errorf("%w: %s", ErrUnknownOpensearchError, b) + } + + e.Err = osErr + e.Status = dummy.Status + + return nil +} diff --git a/opensearchapi/error_test.go b/opensearchapi/error_test.go new file mode 100644 index 000000000..d67dc2eae --- /dev/null +++ b/opensearchapi/error_test.go @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +//go:build !integration + +//nolint:testpackage // need to use the parseError function defined in opensearchapi.go +package opensearchapi + +import ( + "errors" + "fmt" + "io" + "net/http" + "strings" + "testing" + "testing/iotest" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opensearch-project/opensearch-go/v2" +) + +func TestError(t *testing.T) { + t.Run("Error okay", func(t *testing.T) { + resp := &opensearch.Response{ + StatusCode: http.StatusBadRequest, + Body: io.NopCloser( + strings.NewReader(` + { + "error":{ + "root_cause":[{ + "type":"resource_already_exists_exception", + "reason":"index [test/HU2mN_RMRXGcS38j3yV-VQ] already exists", + "index":"test", + "index_uuid":"HU2mN_RMRXGcS38j3yV-VQ" + }], + "type":"resource_already_exists_exception", + "reason":"index [test/HU2mN_RMRXGcS38j3yV-VQ] already exists", + "index":"test", + "index_uuid":"HU2mN_RMRXGcS38j3yV-VQ" + }, + "status":400 + }`), + ), + } + assert.True(t, resp.IsError()) + err := parseError(resp) + var testError Error + require.True(t, errors.As(err, &testError)) + assert.Equal(t, http.StatusBadRequest, testError.Status) + assert.Equal(t, "resource_already_exists_exception", testError.Err.Type) + assert.Equal(t, "index [test/HU2mN_RMRXGcS38j3yV-VQ] already exists", testError.Err.Reason) + assert.Equal(t, "test", testError.Err.Index) + assert.Equal(t, "HU2mN_RMRXGcS38j3yV-VQ", testError.Err.IndexUUID) + assert.NotNil(t, testError.Err.RootCause) + assert.Equal(t, "resource_already_exists_exception", testError.Err.RootCause[0].Type) + assert.Equal(t, "index [test/HU2mN_RMRXGcS38j3yV-VQ] already exists", testError.Err.RootCause[0].Reason) + assert.Equal(t, "test", testError.Err.RootCause[0].Index) + assert.Equal(t, "HU2mN_RMRXGcS38j3yV-VQ", testError.Err.RootCause[0].IndexUUID) + _ = fmt.Sprintf("%s", err) + }) + + t.Run("StringError okay", func(t *testing.T) { + resp := &opensearch.Response{ + StatusCode: http.StatusMethodNotAllowed, + Body: io.NopCloser( + strings.NewReader(` + { + "error": "Incorrect HTTP method for uri [/_doc] and method [POST], allowed: [HEAD, DELETE, PUT, GET]", + "status":405 + }`), + ), + } + assert.True(t, resp.IsError()) + err := parseError(resp) + var testError StringError + require.True(t, errors.As(err, &testError)) + assert.Equal(t, http.StatusMethodNotAllowed, testError.Status) + assert.Contains(t, testError.Err, "Incorrect HTTP method for uri") + _ = fmt.Sprintf("%s", testError) + }) + t.Run("Unexpected", func(t *testing.T) { + cases := []struct { + Name string + Resp *opensearch.Response + WantedErrors []error + }{ + { + Name: "response for StringError", + Resp: &opensearch.Response{ + StatusCode: http.StatusMethodNotAllowed, + Body: io.NopCloser(strings.NewReader(`"Test - Trigger an error"`)), + }, + WantedErrors: []error{ErrJSONUnmarshalBody}, + }, + { + Name: "response string", + Resp: &opensearch.Response{ + StatusCode: http.StatusForbidden, + Body: io.NopCloser(strings.NewReader(`"Test - Trigger an error"`)), + }, + WantedErrors: []error{ErrJSONUnmarshalBody}, + }, + { + Name: "error field string", + Resp: &opensearch.Response{ + StatusCode: http.StatusForbidden, + Body: io.NopCloser(strings.NewReader(`{"error":"test","status":403}`)), + }, + WantedErrors: []error{ErrJSONUnmarshalBody}, + }, + { + Name: "error field object", + Resp: &opensearch.Response{ + StatusCode: http.StatusForbidden, + Body: io.NopCloser(strings.NewReader(`{"error":{"test": "test"},"status":403}`)), + }, + WantedErrors: []error{ErrJSONUnmarshalBody, ErrUnknownOpensearchError}, + }, + { + Name: "response json", + Resp: &opensearch.Response{ + StatusCode: http.StatusNotFound, + Body: io.NopCloser(strings.NewReader(`{"_index":"index","_id":"2","matched":false}`)), + }, + WantedErrors: []error{ErrJSONUnmarshalBody, ErrJSONUnmarshalBody}, + }, + { + Name: "io read error", + Resp: &opensearch.Response{ + StatusCode: http.StatusBadRequest, + Body: io.NopCloser(iotest.ErrReader(errors.New("io reader test"))), + }, + WantedErrors: []error{ErrReadBody}, + }, + { + Name: "empty body", + Resp: &opensearch.Response{StatusCode: http.StatusBadRequest}, + WantedErrors: []error{ErrUnexpectedEmptyBody}, + }, + } + + for _, tt := range cases { + t.Run(tt.Name, func(t *testing.T) { + err := parseError(tt.Resp) + for _, wantedError := range tt.WantedErrors { + assert.True(t, errors.Is(err, wantedError)) + } + }) + } + }) +} diff --git a/opensearchapi/inspect.go b/opensearchapi/inspect.go new file mode 100644 index 000000000..657239a8c --- /dev/null +++ b/opensearchapi/inspect.go @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package opensearchapi + +import "github.com/opensearch-project/opensearch-go/v2" + +// Inspect represents the struct returned by Inspect() func, its main use is to return the opensearch.Response to the user +type Inspect struct { + Response *opensearch.Response +} diff --git a/opensearchapi/internal/test/helper.go b/opensearchapi/internal/test/helper.go new file mode 100644 index 000000000..22adee774 --- /dev/null +++ b/opensearchapi/internal/test/helper.go @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. + +package osapitest + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/wI2L/jsondiff" + + "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" +) + +// Response is a dummy interface to run tests with Inspect() +type Response interface { + Inspect() opensearchapi.Inspect +} + +// CreateFailingClient returns an opensearchapi.Client that always return 400 with an empty object as body +func CreateFailingClient() (*opensearchapi.Client, error) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Body != nil { + defer r.Body.Close() + } + w.WriteHeader(http.StatusBadRequest) + io.Copy(w, strings.NewReader(`{"status": 400, "error": "Test Failing Client Response"}`)) + })) + + return opensearchapi.NewClient(opensearchapi.Config{Client: opensearch.Config{Addresses: []string{ts.URL}}}) +} + +// VerifyInspect validates the returned opensearchapi.Inspect type +func VerifyInspect(t *testing.T, inspect opensearchapi.Inspect) { + t.Helper() + assert.NotEmpty(t, inspect) + assert.Equal(t, http.StatusBadRequest, inspect.Response.StatusCode) + assert.NotEmpty(t, inspect.Response.Body) +} + +// SkipIfBelowVersion skips a test if the cluster version is below a given version +func SkipIfBelowVersion(t *testing.T, client *opensearchapi.Client, majorVersion, patchVersion int64, testName string) { + t.Helper() + resp, err := client.Info(context.Background(), nil) + assert.Nil(t, err) + major, patch, _, err := opensearch.ParseVersion(resp.Version.Number) + assert.Nil(t, err) + if major <= majorVersion && patch <= patchVersion { + t.Skipf("Skiping %s as version %d.%d.x does not support this endpoint", testName, major, patch) + } +} + +// CompareRawJSONwithParsedJSON is a helper function to determin the difference between the parsed JSON and the raw JSON +// this is helpful to detect missing fields in the go structs +func CompareRawJSONwithParsedJSON(t *testing.T, resp any, rawResp *opensearch.Response) { + t.Helper() + if _, ok := os.LookupEnv("OPENSEARCH_GO_SKIP_JSON_COMPARE"); ok { + return + } + require.NotNil(t, rawResp) + + parsedBody, err := json.Marshal(resp) + require.Nil(t, err) + + body, err := io.ReadAll(rawResp.Body) + require.Nil(t, err) + + // If the parsedBody and body does not match, then we need to check if we are adding or removing fields + if string(parsedBody) != string(body) { + patch, err := jsondiff.CompareJSON(body, parsedBody) + assert.Nil(t, err) + operations := make([]jsondiff.Operation, 0) + for _, operation := range patch { + // different opensearch version added more field, only check if we miss some fields + if operation.Type != "add" { + operations = append(operations, operation) + } + } + assert.Empty(t, operations) + if len(operations) == 0 { + return + } + for _, op := range operations { + fmt.Printf("%s\n", op) + } + fmt.Printf("%s\n", body) + } +} diff --git a/opensearchapi/opensearchapi.error.go b/opensearchapi/opensearchapi.error.go deleted file mode 100644 index 5c5a30575..000000000 --- a/opensearchapi/opensearchapi.error.go +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import "fmt" - -// Error represents the API error response. -type Error struct { - Err Err `json:"error"` - Status int `json:"status"` -} - -// Err represents the error of an API error response -type Err struct { - RootCause []RootCause `json:"root_cause"` - Type string `json:"type"` - Reason string `json:"reason"` - Index string `json:"index,omitempty"` - IndexUUID string `json:"index_uudi,omitempty"` -} - -// RootCause represents the root_cause of an API error response -type RootCause struct { - Type string `json:"type"` - Reason string `json:"reason"` - Index string `json:"index,omitempty"` - IndexUUID string `json:"index_uudi,omitempty"` -} - -// Error returns a string. -func (e *Error) Error() string { - return fmt.Sprintf("status: %d, type: %s, reason: %s, root_cause: %s", e.Status, e.Err.Type, e.Err.Reason, e.Err.RootCause) -} diff --git a/opensearchapi/opensearchapi.go b/opensearchapi/opensearchapi.go index 92b728af5..59b41391e 100644 --- a/opensearchapi/opensearchapi.go +++ b/opensearchapi/opensearchapi.go @@ -3,69 +3,181 @@ // The OpenSearch Contributors require contributions made to // this file be licensed under the Apache-2.0 license or a // compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. package opensearchapi import ( + "context" + "encoding/json" + "fmt" + "io" "net/http" "strconv" "time" - "github.com/opensearch-project/opensearch-go/v2/internal/version" + "github.com/opensearch-project/opensearch-go/v2" ) -// Version returns the package version as a string. -// -const Version = version.Client +// Config represents the client configuration +type Config struct { + Client opensearch.Config +} -// Transport defines the interface for an API client. -// -type Transport interface { - Perform(*http.Request) (*http.Response, error) +// Client represents the opensearchapi Client summarizing all API calls +type Client struct { + Client *opensearch.Client + Cat catClient + Cluster clusterClient + Dangling danglingClient + Document documentClient + Indices indicesClient + Nodes nodesClient + Script scriptClient + ComponentTemplate componentTemplateClient + IndexTemplate indexTemplateClient + // Deprecated: uses legacy API (/_template), correct API is /_index_template, use IndexTemplate instead + Template templateClient + DataStream dataStreamClient + PointInTime pointInTimeClient + Ingest ingestClient + Tasks tasksClient + Scroll scrollClient + Snapshot snapshotClient } -// BoolPtr returns a pointer to v. -// -// It is used as a convenience function for converting a bool value -// into a pointer when passing the value to a function or struct field -// which expects a pointer. -// -func BoolPtr(v bool) *bool { return &v } +// clientInit inits the Client with all sub clients +func clientInit(rootClient *opensearch.Client) *Client { + client := &Client{ + Client: rootClient, + } + client.Cat = catClient{apiClient: client} + client.Indices = indicesClient{ + apiClient: client, + Alias: aliasClient{apiClient: client}, + Mapping: mappingClient{apiClient: client}, + Settings: settingsClient{apiClient: client}, + } + client.Nodes = nodesClient{apiClient: client} + client.Cluster = clusterClient{apiClient: client} + client.Dangling = danglingClient{apiClient: client} + client.Script = scriptClient{apiClient: client} + client.Document = documentClient{apiClient: client} + client.ComponentTemplate = componentTemplateClient{apiClient: client} + client.IndexTemplate = indexTemplateClient{apiClient: client} + client.Template = templateClient{apiClient: client} + client.DataStream = dataStreamClient{apiClient: client} + client.PointInTime = pointInTimeClient{apiClient: client} + client.Ingest = ingestClient{apiClient: client} + client.Tasks = tasksClient{apiClient: client} + client.Scroll = scrollClient{apiClient: client} + client.Snapshot = snapshotClient{ + apiClient: client, + Repository: repositoryClient{apiClient: client}, + } -// IntPtr returns a pointer to v. -// -// It is used as a convenience function for converting an int value -// into a pointer when passing the value to a function or struct field -// which expects a pointer. -// -func IntPtr(v int) *int { return &v } + return client +} + +// NewClient returns a opensearchapi client +func NewClient(config Config) (*Client, error) { + rootClient, err := opensearch.NewClient(config.Client) + if err != nil { + return nil, err + } + + return clientInit(rootClient), nil +} + +// NewDefaultClient returns a opensearchapi client using defaults +func NewDefaultClient() (*Client, error) { + rootClient, err := opensearch.NewClient(opensearch.Config{ + Addresses: []string{"http://localhost:9200"}, + }) + if err != nil { + return nil, err + } + + return clientInit(rootClient), nil +} + +// do calls the opensearch.Client.Do() and checks the response for openseach api errors +func (c *Client) do(ctx context.Context, req opensearch.Request, dataPointer any) (*opensearch.Response, error) { + resp, err := c.Client.Do(ctx, req, dataPointer) + if err != nil { + return nil, err + } + + if resp.IsError() { + if dataPointer != nil { + return resp, parseError(resp) + } else { + return resp, fmt.Errorf("status: %s", resp.Status()) + } + } + + return resp, nil +} + +// praseError tries to parse the opensearch api error into an custom error +func parseError(resp *opensearch.Response) error { + if resp.Body == nil { + return fmt.Errorf("%w, status: %s", ErrUnexpectedEmptyBody, resp.Status()) + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("%w: %w", ErrReadBody, err) + } + + if resp.StatusCode == http.StatusMethodNotAllowed { + var apiError StringError + if err = json.Unmarshal(body, &apiError); err != nil { + return fmt.Errorf("%w: %w", ErrJSONUnmarshalBody, err) + } + return apiError + } + + // ToDo: Parse 404 errors separate as they are not in one standard format + // https://github.com/opensearch-project/OpenSearch/issues/9988 + + var apiError Error + if err = json.Unmarshal(body, &apiError); err != nil { + return fmt.Errorf("%w: %w", ErrJSONUnmarshalBody, err) + } + + return apiError +} // formatDuration converts duration to a string in the format -// accepted by Elasticsearch. -// +// accepted by Opensearch. func formatDuration(d time.Duration) string { if d < time.Millisecond { return strconv.FormatInt(int64(d), 10) + "nanos" } + return strconv.FormatInt(int64(d)/int64(time.Millisecond), 10) + "ms" } + +// ToPointer converts any value to a pointer, mainly used for request parameters +func ToPointer[V any](value V) *V { + return &value +} + +// ResponseShards is a sub type of api repsonses containing information about shards +type ResponseShards struct { + Total int `json:"total"` + Successful int `json:"successful"` + Failed int `json:"failed"` + Failures []ResponseShardsFailure `json:"failures"` + Skipped int `json:"skipped"` +} + +// ResponseShardsFailure is a sub type of ReponseShards containing information about a failed shard +type ResponseShardsFailure struct { + Shard int `json:"shard"` + Index any `json:"index"` + Reason struct { + Type string `json:"type"` + Reason string `json:"reason"` + } `json:"reason"` +} diff --git a/opensearchapi/opensearchapi.response.go b/opensearchapi/opensearchapi.response.go deleted file mode 100644 index 0f4c561f4..000000000 --- a/opensearchapi/opensearchapi.response.go +++ /dev/null @@ -1,130 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "strings" -) - -// Response represents the API response. -type Response struct { - StatusCode int - Header http.Header - Body io.ReadCloser -} - -// String returns the response as a string. -// -// The intended usage is for testing or debugging only. -func (r *Response) String() string { - var ( - out = new(bytes.Buffer) - b1 = bytes.NewBuffer([]byte{}) - b2 = bytes.NewBuffer([]byte{}) - tr io.Reader - ) - - if r != nil && r.Body != nil { - tr = io.TeeReader(r.Body, b1) - defer r.Body.Close() - - if _, err := io.Copy(b2, tr); err != nil { - out.WriteString(fmt.Sprintf("", err)) - return out.String() - } - defer func() { r.Body = ioutil.NopCloser(b1) }() - } - - if r != nil { - out.WriteString(fmt.Sprintf("[%d %s]", r.StatusCode, http.StatusText(r.StatusCode))) - if r.StatusCode > 0 { - out.WriteRune(' ') - } - } else { - out.WriteString("[0 ]") - } - - if r != nil && r.Body != nil { - out.ReadFrom(b2) // errcheck exclude (*bytes.Buffer).ReadFrom - } - - return out.String() -} - -// Status returns the response status as a string. -func (r *Response) Status() string { - var b strings.Builder - if r != nil { - b.WriteString(strconv.Itoa(r.StatusCode)) - b.WriteString(" ") - b.WriteString(http.StatusText(r.StatusCode)) - } - return b.String() -} - -// IsError returns true when the response status indicates failure. -func (r *Response) IsError() bool { - return r.StatusCode > 299 -} - -// Warnings returns the deprecation warnings from response headers. -func (r *Response) Warnings() []string { - return r.Header["Warning"] -} - -// HasWarnings returns true when the response headers contain deprecation warnings. -func (r *Response) HasWarnings() bool { - return len(r.Warnings()) > 0 -} - -// Err returns an error when the response status indicates failures. -func (r *Response) Err() error { - if r.IsError() { - if r.Body == nil { - return fmt.Errorf(r.Status()) - } - body, err := io.ReadAll(r.Body) - if err != nil { - return fmt.Errorf(r.Status()) - } - var e *Error - err = json.Unmarshal(body, &e) - if err == nil && !reflect.ValueOf(e.Err).IsZero() { - return e - } - return fmt.Errorf("status: %d, error: %s", r.StatusCode, string(body)) - } - return nil -} diff --git a/opensearchapi/opensearchapi_benchmark_test.go b/opensearchapi/opensearchapi_benchmark_test.go deleted file mode 100644 index 5b9095590..000000000 --- a/opensearchapi/opensearchapi_benchmark_test.go +++ /dev/null @@ -1,315 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package opensearchapi_test - -import ( - "context" - "errors" - "io/ioutil" - "net/http" - "strconv" - "strings" - "testing" - - "github.com/opensearch-project/opensearch-go/v2" - "github.com/opensearch-project/opensearch-go/v2/opensearchapi" -) - -// TODO: Refactor into a shared mock/testing package - -var ( - defaultResponse = &http.Response{ - StatusCode: 200, - Header: http.Header{}, - Body: ioutil.NopCloser(strings.NewReader("MOCK")), - } - defaultRoundTripFn = func(*http.Request) (*http.Response, error) { return defaultResponse, nil } - errorRoundTripFn = func(request *http.Request) (*http.Response, error) { - if request.URL.Path == "/" { - return &http.Response{ - StatusCode: 200, - Header: http.Header{}, - Body: ioutil.NopCloser(strings.NewReader("{}")), - }, nil - } - return &http.Response{ - Header: http.Header{}, - StatusCode: 400, - Body: ioutil.NopCloser(strings.NewReader(` - { "error" : { - "root_cause" : [ - { - "type" : "parsing_exception", - "reason" : "no [query] registered for [foo]", - "line" : 1, - "col" : 22 - } - ], - "type" : "parsing_exception", - "reason" : "no [query] registered for [foo]", - "line" : 1, - "col" : 22 - }, - "status" : 400 - }`)), - }, nil - } -) - -type FakeTransport struct { - RoundTripFn func(*http.Request) (*http.Response, error) -} - -func (t *FakeTransport) RoundTrip(req *http.Request) (*http.Response, error) { - return t.RoundTripFn(req) -} - -func newFakeClient(b *testing.B) *opensearch.Client { - cfg := opensearch.Config{Transport: &FakeTransport{RoundTripFn: defaultRoundTripFn}} - client, err := opensearch.NewClient(cfg) - - if err != nil { - b.Fatalf("Unexpected error when creating a client: %s", err) - } - - return client -} - -func newFakeClientWithError(b *testing.B) *opensearch.Client { - cfg := opensearch.Config{Transport: &FakeTransport{RoundTripFn: errorRoundTripFn}} - client, err := opensearch.NewClient(cfg) - - if err != nil { - b.Fatalf("Unexpected error when creating a client: %s", err) - } - - return client -} - -func BenchmarkAPI(b *testing.B) { - var client = newFakeClient(b) - var fakeClientWithError = newFakeClientWithError(b) - - b.Run("client.Info() ", func(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := client.Info(); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("client.Info() WithContext ", func(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := client.Info(client.Info.WithContext(context.Background())); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("InfoRequest{}.Do() ", func(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - req := opensearchapi.InfoRequest{} - if _, err := req.Do(context.Background(), client); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("client.Cluster.Health() ", func(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := client.Cluster.Health(); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("client.Cluster.Health() With() ", func(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := client.Cluster.Health( - client.Cluster.Health.WithContext(context.Background()), - client.Cluster.Health.WithLevel("indices"), - client.Cluster.Health.WithPretty(), - ) - - if err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("ClusterHealthRequest{}.Do() ", func(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - req := opensearchapi.ClusterHealthRequest{} - if _, err := req.Do(context.Background(), client); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("ClusterHealthRequest{...}.Do() ", func(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - req := opensearchapi.ClusterHealthRequest{Level: "indices", Pretty: true} - if _, err := req.Do(context.Background(), client); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("client.Index() With() ", func(b *testing.B) { - indx := "test" - body := strings.NewReader(`{"title" : "Test"}`) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := client.Index( - indx, - body, - client.Index.WithDocumentID("1"), - client.Index.WithRefresh("true"), - client.Index.WithContext(context.Background()), - client.Index.WithRefresh("true"), - client.Index.WithPretty(), - client.Index.WithTimeout(100), - ) - - if err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("IndexRequest{...}.Do() ", func(b *testing.B) { - b.ResetTimer() - var body strings.Builder - for i := 0; i < b.N; i++ { - docID := strconv.FormatInt(int64(i), 10) - body.Reset() - body.WriteString(`{"foo" : "bar `) - body.WriteString(docID) - body.WriteString(` " }`) - - req := opensearchapi.IndexRequest{ - Index: "test", - DocumentID: docID, - Body: strings.NewReader(body.String()), - Refresh: "true", - Pretty: true, - Timeout: 100, - } - - if _, err := req.Do(context.Background(), client); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("IndexRequest{...}.Do() reused ", func(b *testing.B) { - b.ResetTimer() - var body strings.Builder - - req := opensearchapi.IndexRequest{} - req.Index = "test" - req.Refresh = "true" - req.Pretty = true - req.Timeout = 100 - - for i := 0; i < b.N; i++ { - docID := strconv.FormatInt(int64(i), 10) - body.Reset() - body.WriteString(`{"foo" : "bar `) - body.WriteString(docID) - body.WriteString(` " }`) - req.DocumentID = docID - req.Body = strings.NewReader(body.String()) - - if _, err := req.Do(context.Background(), client); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("client.Search() ", func(b *testing.B) { - body := strings.NewReader(`{"query" : { "match_all" : {} } }`) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := client.Search(client.Search.WithContext(context.Background()), client.Search.WithBody(body)) - - if err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("client.Search() with error ", func(b *testing.B) { - body := strings.NewReader(`{}`) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := fakeClientWithError.Search(fakeClientWithError.Search.WithContext(context.Background()), fakeClientWithError.Search.WithBody(body)) - - if err != nil { - var opensearchError *opensearchapi.Error - if !errors.As(err, &opensearchError) { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - } - }) - - b.Run("SearchRequest{...}.Do() ", func(b *testing.B) { - body := strings.NewReader(`{"query" : { "match_all" : {} } }`) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - req := opensearchapi.SearchRequest{Body: body} - if _, err := req.Do(context.Background(), client); err != nil { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - }) - - b.Run("SearchRequest{...}.Do() with error ", func(b *testing.B) { - body := strings.NewReader(`{}`) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - req := opensearchapi.SearchRequest{Body: body} - if _, err := req.Do(context.Background(), fakeClientWithError); err != nil { - var opensearchError *opensearchapi.Error - if !errors.As(err, &opensearchError) { - b.Errorf("Unexpected error when getting a response: %s", err) - } - } - } - }) -} diff --git a/opensearchapi/opensearchapi_integration_test.go b/opensearchapi/opensearchapi_integration_test.go deleted file mode 100644 index a0d8ec249..000000000 --- a/opensearchapi/opensearchapi_integration_test.go +++ /dev/null @@ -1,443 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -//go:build integration -// +build integration - -package opensearchapi_test - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "strings" - "testing" - "time" - "github.com/stretchr/testify/assert" - - "github.com/opensearch-project/opensearch-go/v2" - "github.com/opensearch-project/opensearch-go/v2/opensearchapi" -) - -func createTestIndex(client *opensearch.Client, index string) error { - var buf bytes.Buffer - // Index data - // - for j := 1; j <= 1000; j++ { - meta := []byte(fmt.Sprintf(`{ "index" : { "_id" : "%d" } }%s`, j, "\n")) - data := []byte(`{"content":"` + strings.Repeat("ABC", 100) + `"}`) - data = append(data, "\n"...) - - buf.Grow(len(meta) + len(data)) - buf.Write(meta) - buf.Write(data) - } - _, err := client.Bulk(bytes.NewReader(buf.Bytes()), client.Bulk.WithIndex(index), client.Bulk.WithRefresh("true")) - return err -} - -func TestAPI(t *testing.T) { - t.Run("Search", func(t *testing.T) { - client, err := opensearch.NewDefaultClient() - if err != nil { - t.Fatalf("Error creating the client: %s\n", err) - } - - client.Cluster.Health(client.Cluster.Health.WithWaitForStatus("yellow")) - res, err := client.Search(client.Search.WithTimeout(500 * time.Millisecond)) - if err != nil { - t.Fatalf("Error getting the response: %s\n", err) - } - defer res.Body.Close() - - var d map[string]interface{} - err = json.NewDecoder(res.Body).Decode(&d) - if err != nil { - t.Fatalf("Error parsing the response: %s\n", err) - } - fmt.Printf("took=%vms\n", d["took"]) - }) - - t.Run("Headers", func(t *testing.T) { - client, err := opensearch.NewDefaultClient() - if err != nil { - t.Fatalf("Error creating the client: %s\n", err) - } - - res, err := client.Info(client.Info.WithHeader(map[string]string{"Accept": "application/yaml"})) - if err != nil { - t.Fatalf("Error getting the response: %s\n", err) - } - defer res.Body.Close() - - if !strings.HasPrefix(res.String(), "[200 OK] ---") { - t.Errorf("Unexpected response body: doesn't start with '[200 OK] ---'; %s", res.String()) - } - }) - - t.Run("OpaqueID", func(t *testing.T) { - var ( - res *opensearchapi.Response - err error - - requestID = "reindex-123" - ) - - client, err := opensearch.NewDefaultClient() - if err != nil { - t.Fatalf("Error creating the client: %s\n", err) - } - - // Prepare indices - // - client.Indices.Delete([]string{"test", "reindexed"}, client.Indices.Delete.WithIgnoreUnavailable(true)) - - // Index data - // - err = createTestIndex(client, "test") - if err != nil { - t.Fatalf("Failed to index data: %s", err) - } - - // Add a document to the index. - document := strings.NewReader(`{ - "title": "Moneyball", - "director": "Bennett Miller", - "year": "2011" - }`) - - docId := "1" - req := opensearchapi.IndexRequest{ - Index: "test", - DocumentID: docId, - Body: document, - } - insertResponse, err := req.Do(context.Background(), client) - if err != nil { - fmt.Println("failed to insert document ", err) - } - defer insertResponse.Body.Close() - - // Get the document with source filters - getSourceRequest := opensearchapi.GetSourceRequest{ - Index: "test", - DocumentID: "1", - Source: []string{"title"}, - } - getSourceResponse, err := getSourceRequest.Do(context.Background(), client) - if err != nil { - fmt.Println("failed to get source ", err) - } - assert.Equal(t, 200, getSourceResponse.StatusCode) - assert.Contains(t, getSourceResponse.String(), "title") - assert.NotContains(t, getSourceResponse.String(), "director") - defer getSourceResponse.Body.Close() - - getSourceRequest = opensearchapi.GetSourceRequest{ - Index: "test", - DocumentID: "1", - SourceIncludes: []string{"title"}, - } - getSourceResponse, err = getSourceRequest.Do(context.Background(), client) - if err != nil { - fmt.Println("failed to get source ", err) - } - assert.Equal(t, 200, getSourceResponse.StatusCode) - assert.Contains(t, getSourceResponse.String(), "title") - assert.NotContains(t, getSourceResponse.String(), "director") - defer getSourceResponse.Body.Close() - - getSourceRequest = opensearchapi.GetSourceRequest{ - Index: "test", - DocumentID: "1", - SourceExcludes: []string{"title"}, - } - getSourceResponse, err = getSourceRequest.Do(context.Background(), client) - if err != nil { - fmt.Println("failed to get source ", err) - } - assert.Equal(t, 200, getSourceResponse.StatusCode) - assert.Contains(t, getSourceResponse.String(), "director") - assert.NotContains(t, getSourceResponse.String(), "title") - defer getSourceResponse.Body.Close() - - // Launch reindexing task with wait_for_completion=false - // - res, err = client.Reindex( - strings.NewReader(`{"source":{"index":"test"}, "dest": {"index":"reindexed"}}`), - client.Reindex.WithWaitForCompletion(false), - client.Reindex.WithRequestsPerSecond(1), - client.Reindex.WithOpaqueID(requestID)) - if err != nil { - t.Fatalf("Failed to reindex: %s", err) - } - time.Sleep(10 * time.Millisecond) - - res, err = client.Tasks.List(client.Tasks.List.WithPretty()) - if err != nil { - t.Fatalf("ERROR: %s", err) - } - res.Body.Close() - - // Get the list of tasks - // - res, err = client.Tasks.List(client.Tasks.List.WithPretty()) - if err != nil { - t.Fatalf("ERROR: %s", err) - } - defer res.Body.Close() - - type task struct { - Node string - ID int - Action string - RunningTime time.Duration `json:"running_time_in_nanos"` - Cancellable bool - Headers map[string]interface{} - } - - type node struct { - Tasks map[string]task - } - - var nodes map[string]map[string]node - if err := json.NewDecoder(res.Body).Decode(&nodes); err != nil { - t.Fatalf("Failed to decode response: %s", err) - } - - var hasReindexTask bool - - for _, n := range nodes["nodes"] { - for taskID, task := range n.Tasks { - if task.Headers["X-Opaque-Id"] == requestID { - if strings.Contains(task.Action, "reindex") { - hasReindexTask = true - } - fmt.Printf("* %s, %s | %s (%s)\n", requestID, taskID, task.Action, task.RunningTime) - } - } - } - - if !hasReindexTask { - t.Errorf("Expected reindex task in %+v", nodes["nodes"]) - } - - for _, n := range nodes["nodes"] { - for taskID, task := range n.Tasks { - if task.Headers["X-Opaque-Id"] == requestID { - if task.Cancellable { - fmt.Printf("=> Closing task %s\n", taskID) - res, err = client.Tasks.Cancel(client.Tasks.Cancel.WithTaskID(taskID)) - if err != nil { - t.Fatalf("ERROR: %s", err) - } - defer res.Body.Close() - } - } - } - } - }) - t.Run("Snapshot", func(t *testing.T) { - // Functio to perform requests - // - opensearchDo := func(ctx context.Context, client *opensearch.Client, req opensearchapi.Request, msg string, t *testing.T) { - _, err := req.Do(ctx, client) - if err != nil { - var opensearchError *opensearchapi.Error - if errors.As(err, &opensearchError) { - if opensearchError.Err.Type == "snapshot_missing_exception" { - return - } - t.Fatalf("Failed to %s: %s", msg, err) - } - } - } - - // Create Client - // - client, err := opensearch.NewDefaultClient() - if err != nil { - t.Fatalf("Error creating the client: %s\n", err) - } - - // Pre Cleanup indices - // - iDeleteReq := &opensearchapi.IndicesDeleteRequest{ - Index: []string{"test", "test_restored"}, - IgnoreUnavailable: opensearchapi.BoolPtr(true), - } - ctx := context.Background() - opensearchDo(ctx, client, iDeleteReq, "index data", t) - - // Index data - // - err = createTestIndex(client, "test") - if err != nil { - t.Fatalf("Failed to index data: %s", err) - } - - // Test Snapshot functions - // - sRepoCreateReq := &opensearchapi.SnapshotCreateRepositoryRequest{ - Body: bytes.NewBufferString(`{"type":"fs","settings":{"location":"/usr/share/opensearch/mnt"}}`), - Repository: "snapshot-test", - } - opensearchDo(ctx, client, sRepoCreateReq, "create Snapshot Repository", t) - - sRepoVerifyReq := &opensearchapi.SnapshotVerifyRepositoryRequest{ - Repository: "snapshot-test", - } - opensearchDo(ctx, client, sRepoVerifyReq, "verify Snapshot Repository", t) - - sDeleteReq := &opensearchapi.SnapshotDeleteRequest{ - Snapshot: []string{"test", "clone-test"}, - Repository: "snapshot-test", - } - opensearchDo(ctx, client, sDeleteReq, "delete Snapshots", t) - - sCreateReq := &opensearchapi.SnapshotCreateRequest{ - Body: bytes.NewBufferString(`{"indices":"test","ignore_unavailable":true,"include_global_state":false,"partial":false}`), - Snapshot: "test", - Repository: "snapshot-test", - WaitForCompletion: opensearchapi.BoolPtr(true), - } - opensearchDo(ctx, client, sCreateReq, "create Snapshot", t) - - sCloneReq := &opensearchapi.SnapshotCloneRequest{ - Body: bytes.NewBufferString(`{"indices":"*"}`), - Snapshot: "test", - TargetSnapshot: "clone-test", - Repository: "snapshot-test", - } - opensearchDo(ctx, client, sCloneReq, "clone Snapshot", t) - - sGetReq := &opensearchapi.SnapshotGetRequest{ - Snapshot: []string{"test", "clone-test"}, - Repository: "snapshot-test", - } - opensearchDo(ctx, client, sGetReq, "get Snapshots", t) - - sStatusReq := &opensearchapi.SnapshotGetRequest{ - Snapshot: []string{"test", "clone-test"}, - Repository: "snapshot-test", - } - opensearchDo(ctx, client, sStatusReq, "get Snapshot status", t) - - sRestoreReq := &opensearchapi.SnapshotRestoreRequest{ - Body: bytes.NewBufferString( - `{ - "indices":"test", - "ignore_unavailable":true, - "include_global_state":false, - "partial":false, - "rename_pattern": "(.+)", - "rename_replacement":"$1_restored" - }`, - ), - Snapshot: "clone-test", - Repository: "snapshot-test", - WaitForCompletion: opensearchapi.BoolPtr(true), - } - opensearchDo(ctx, client, sRestoreReq, "restore Snapshot", t) - - opensearchDo(ctx, client, sDeleteReq, "delete Snapshots", t) - opensearchDo(ctx, client, iDeleteReq, "index data", t) - }) - t.Run("Point_in_Time", func(t *testing.T) { - var ( - err error - major, minor int64 - data opensearchapi.InfoResp - ) - index := "test" - - // Create Client - // - client, err := opensearch.NewDefaultClient() - if err != nil { - t.Fatalf("Error creating the client: %s\n", err) - } - - // Skip test if Cluster version is below 2.4.0 - infoResp, err := client.Info() - if err != nil { - t.Fatalf("Error getting the cluster info: %s\n", err) - } - if err = json.NewDecoder(infoResp.Body).Decode(&data); err != nil { - t.Fatalf("Error parsing the cluster info: %s\n", err) - } - major, minor, _, err = opensearch.ParseVersion(data.Version.Number) - if err != nil { - t.Fatalf("Error parsing the cluster version") - } - if major <= 2 && minor < 4 { - return - } - - // Cleanup all existing Pits - // - resp, _, err := client.PointInTime.Delete(client.PointInTime.Delete.WithPitID("_all")) - if err != nil { - if resp != nil && resp.StatusCode != 404 { - t.Fatalf("Failed to Delete all Pits: %s", err) - } - } - - // Index data - // - err = createTestIndex(client, index) - if err != nil { - t.Fatalf("Failed to index data: %s", err) - } - - // Create a Pit - // - keepAlive, _ := time.ParseDuration("5m") - _, pitCreateResp, err := client.PointInTime.Create(client.PointInTime.Create.WithKeepAlive(keepAlive), client.PointInTime.Create.WithIndex(index)) - if err != nil { - t.Fatalf("Failed to create Pit: %s", err) - } - - // Get all Pits - // - _, pitGetResp, err := client.PointInTime.Get() - if err != nil { - t.Fatalf("Failed to get Pits: %s", err) - } - - // Delete the create Pit - // - _, pitDeleteResp, err := client.PointInTime.Delete(client.PointInTime.Delete.WithPitID(pitCreateResp.PitID)) - if err != nil { - t.Fatalf("Failed to delete Pit: %s", err) - } - if (pitCreateResp.PitID != pitGetResp.Pits[0].PitID) || (pitCreateResp.PitID != pitDeleteResp.Pits[0].PitID) { - t.Fatalf("The create Pit does not match the Get Pit or Deleted Pit") - } - }) -} diff --git a/opensearchapi/opensearchapi_request_internal_test.go b/opensearchapi/opensearchapi_request_internal_test.go deleted file mode 100644 index e43bf7aa9..000000000 --- a/opensearchapi/opensearchapi_request_internal_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -// +build !integration - -package opensearchapi - -import ( - "bytes" - "io" - "net/http" - "strings" - "testing" -) - -func TestAPIRequest(t *testing.T) { - var ( - body string - req *http.Request - err error - ) - - t.Run("newRequest", func(t *testing.T) { - req, err = newRequest("GET", "/foo", nil) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - - if req.Method != "GET" { - t.Errorf("Unexpected method %s, want GET", req.Method) - } - if req.URL.String() != "/foo" { - t.Errorf("Unexpected URL %s, want /foo", req.URL) - } - - body = `{"foo":"bar"}` - req, err = newRequest("GET", "/foo", strings.NewReader(body)) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - - if _, ok := req.Body.(io.ReadCloser); !ok { - t.Errorf("Unexpected type for req.Body: %T", req.Body) - } - if int(req.ContentLength) != len(body) { - t.Errorf("Unexpected length of req.Body, got=%d, want=%d", req.ContentLength, len(body)) - } - - req, err = newRequest("GET", "/foo", bytes.NewBuffer([]byte(body))) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - if _, ok := req.Body.(io.ReadCloser); !ok { - t.Errorf("Unexpected type for req.Body: %T", req.Body) - } - req, err = newRequest("GET", "/foo", bytes.NewReader([]byte(body))) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - if _, ok := req.Body.(io.ReadCloser); !ok { - t.Errorf("Unexpected type for req.Body: %T", req.Body) - } - }) -} diff --git a/opensearchapi/opensearchapi_response_internal_test.go b/opensearchapi/opensearchapi_response_internal_test.go deleted file mode 100644 index 0cdc7c61f..000000000 --- a/opensearchapi/opensearchapi_response_internal_test.go +++ /dev/null @@ -1,195 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// -// The OpenSearch Contributors require contributions made to -// this file be licensed under the Apache-2.0 license or a -// compatible open source license. -// -// Modifications Copyright OpenSearch Contributors. See -// GitHub history for details. - -// Licensed to Elasticsearch B.V. under one or more contributor -// license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright -// ownership. Elasticsearch B.V. licenses this file to you under -// the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -//go:build !integration -// +build !integration - -package opensearchapi - -import ( - "errors" - "io" - "io/ioutil" - "net/http" - "strings" - "testing" -) - -type errReader struct{} - -func (errReader) Read(p []byte) (n int, err error) { return 1, errors.New("MOCK ERROR") } - -func TestAPIResponse(t *testing.T) { - var ( - body string - res *Response - err error - ) - - t.Run("String", func(t *testing.T) { - body = `{"foo":"bar"}` - - res = &Response{StatusCode: 200, Body: ioutil.NopCloser(strings.NewReader(body))} - - expected := `[200 OK]` + ` ` + body - if res.String() != expected { - t.Errorf("Unexpected response: %s, want: %s", res.String(), expected) - } - }) - - t.Run("String with empty response", func(t *testing.T) { - res = &Response{} - - if res.String() != "[0 ]" { - t.Errorf("Unexpected response: %s", res.String()) - } - }) - - t.Run("String with nil response", func(t *testing.T) { - res = nil - - if res.String() != "[0 ]" { - t.Errorf("Unexpected response: %s", res.String()) - } - }) - - t.Run("String Error", func(t *testing.T) { - res = &Response{StatusCode: 200, Body: ioutil.NopCloser(errReader{})} - - if !strings.Contains(res.String(), `error reading response`) { - t.Errorf("Expected response string to contain 'error reading response', got: %s", res.String()) - } - }) - - t.Run("Status", func(t *testing.T) { - res = &Response{StatusCode: 404} - - if res.Status() != `404 Not Found` { - t.Errorf("Unexpected response status text: %s, want: 404 Not Found", res.Status()) - } - }) - - t.Run("IsError", func(t *testing.T) { - res = &Response{StatusCode: 201} - - if res.IsError() { - t.Errorf("Unexpected error for response: %s", res.Status()) - } - - res = &Response{StatusCode: 403} - - if !res.IsError() { - t.Errorf("Expected error for response: %s", res.Status()) - } - }) - - t.Run("Error", func(t *testing.T) { - res = &Response{StatusCode: 201} - - if err = res.Err(); err != nil { - t.Errorf("Unexpected error for response: %s", res.Status()) - } - - res = &Response{StatusCode: 403} - - if err = res.Err(); err == nil { - t.Errorf("Expected error for response: %s", res.Status()) - } - - res = &Response{ - StatusCode: 404, - Body: io.NopCloser( - strings.NewReader(` - { - "_index":"index", - "_id":"2", - "matched":false - }`), - ), - } - err = res.Err() - if err == nil { - t.Errorf("Expected error for response: %s", res.Status()) - } - var errTest *Error - if errors.As(err, &errTest) { - t.Errorf("Expected error NOT to be of type opensearchapi.Error: %T", err) - } - - res = &Response{ - StatusCode: 400, - Body: io.NopCloser( - strings.NewReader(` - { - "error":{ - "root_cause":[{ - "type":"resource_already_exists_exception", - "reason":"index [test/HU2mN_RMRXGcS38j3yV-VQ] already exists", - "index":"test", - "index_uuid":"HU2mN_RMRXGcS38j3yV-VQ" - }], - "type":"resource_already_exists_exception", - "reason":"index [test/HU2mN_RMRXGcS38j3yV-VQ] already exists", - "index":"test", - "index_uuid":"HU2mN_RMRXGcS38j3yV-VQ" - }, - "status":400 - }`)), - } - - err = res.Err() - if err == nil { - t.Errorf("Expected error for response: %s", res.Status()) - } - if !errors.As(err, &errTest) { - t.Errorf("Expected error to be of type opensearchapi.Error: %T", err) - } - if errTest.Status != 400 || - errTest.Err.Reason != "index [test/HU2mN_RMRXGcS38j3yV-VQ] already exists" || - errTest.Err.Type != "resource_already_exists_exception" || - len(errTest.Err.RootCause) != 1 || - errTest.Err.RootCause[0].Type != "resource_already_exists_exception" || - errTest.Err.RootCause[0].Reason != "index [test/HU2mN_RMRXGcS38j3yV-VQ] already exists" { - - t.Errorf("Reponse Error was not parsed correctly") - } - }) - - t.Run("Warnings", func(t *testing.T) { - hdr := http.Header{} - hdr.Add("Warning", "Foo 1") - hdr.Add("Warning", "Foo 2") - res = &Response{StatusCode: 201, Header: hdr} - - if !res.HasWarnings() { - t.Errorf("Expected response to have warnings") - } - - if len(res.Warnings()) != 2 { - t.Errorf("Expected [2] warnings, got: %d", len(res.Warnings())) - } - }) -} diff --git a/opensearchapi/test/.gitignore b/opensearchapi/test/.gitignore deleted file mode 100644 index b30909591..000000000 --- a/opensearchapi/test/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -go.sum -*_test.go diff --git a/opensearchapi/test/go.mod b/opensearchapi/test/go.mod deleted file mode 100644 index edf66123e..000000000 --- a/opensearchapi/test/go.mod +++ /dev/null @@ -1,11 +0,0 @@ -module github.com/opensearch-project/opensearch-go/v2/opensearch/test - -go 1.11 - -replace github.com/opensearch-project/opensearch-go/v2 => ../../ - -require ( - github.com/opensearch-project/opensearch-go/v2 v2.2.0 - - gopkg.in/yaml.v2 v2.4.0 -) diff --git a/opensearchtransport/metrics.go b/opensearchtransport/metrics.go index 7a8252c61..442d04ae5 100644 --- a/opensearchtransport/metrics.go +++ b/opensearchtransport/metrics.go @@ -97,7 +97,8 @@ func (c *Client) Metrics() (Metrics, error) { } if pool, ok := c.pool.(connectionable); ok { - for _, c := range pool.connections() { + connections := pool.connections() + for idx, c := range connections { c.Lock() cm := ConnectionMetric{ @@ -107,7 +108,7 @@ func (c *Client) Metrics() (Metrics, error) { } if !c.DeadSince.IsZero() { - cm.DeadSince = &c.DeadSince + cm.DeadSince = &connections[idx].DeadSince } if c.ID != "" { diff --git a/opensearchutil/bulk_indexer.go b/opensearchutil/bulk_indexer.go index 0ed320a6b..8da0b91bc 100644 --- a/opensearchutil/bulk_indexer.go +++ b/opensearchutil/bulk_indexer.go @@ -38,12 +38,12 @@ import ( "sync/atomic" "time" - "github.com/opensearch-project/opensearch-go/v2" "github.com/opensearch-project/opensearch-go/v2/opensearchapi" ) +const defaultFlushInterval = 30 * time.Second + // BulkIndexer represents a parallel, asynchronous, efficient indexer for OpenSearch. -// type BulkIndexer interface { // Add adds an item to the indexer. It returns an error when the item cannot be added. // Use the OnSuccess and OnFailure callbacks to get the operation result for the item. @@ -62,15 +62,13 @@ type BulkIndexer interface { } // BulkIndexerConfig represents configuration of the indexer. -// type BulkIndexerConfig struct { NumWorkers int // The number of workers. Defaults to runtime.NumCPU(). FlushBytes int // The flush threshold in bytes. Defaults to 5MB. FlushInterval time.Duration // The flush threshold as duration. Defaults to 30sec. - Client *opensearch.Client // The OpenSearch client. - Decoder BulkResponseJSONDecoder // A custom JSON decoder. - DebugLogger BulkIndexerDebugLogger // An optional logger for debugging. + Client *opensearchapi.Client // The OpenSearch client. + DebugLogger BulkIndexerDebugLogger // An optional logger for debugging. OnError func(context.Context, error) // Called for indexer errors. OnFlushStart func(context.Context) context.Context // Called when the flush starts. @@ -79,7 +77,6 @@ type BulkIndexerConfig struct { // Parameters of the Bulk API. Index string ErrorTrace bool - FilterPath []string Header http.Header Human bool Pipeline string @@ -94,7 +91,6 @@ type BulkIndexerConfig struct { } // BulkIndexerStats represents the indexer statistics. -// type BulkIndexerStats struct { NumAdded uint64 NumFlushed uint64 @@ -107,7 +103,6 @@ type BulkIndexerStats struct { } // BulkIndexerItem represents an indexer item. -// type BulkIndexerItem struct { Index string Action string @@ -123,8 +118,8 @@ type BulkIndexerItem struct { Body io.ReadSeeker RetryOnConflict *int - OnSuccess func(context.Context, BulkIndexerItem, BulkIndexerResponseItem) // Per item - OnFailure func(context.Context, BulkIndexerItem, BulkIndexerResponseItem, error) // Per item + OnSuccess func(context.Context, BulkIndexerItem, opensearchapi.BulkRespItem) // Per item + OnFailure func(context.Context, BulkIndexerItem, opensearchapi.BulkRespItem, error) // Per item } type bulkActionMetadata struct { @@ -141,61 +136,7 @@ type bulkActionMetadata struct { RetryOnConflict *int `json:"retry_on_conflict,omitempty"` } -// BulkIndexerResponse represents the OpenSearch response. -// -type BulkIndexerResponse struct { - Took int `json:"took"` - HasErrors bool `json:"errors"` - Items []map[string]BulkIndexerResponseItem `json:"items,omitempty"` -} - -// BulkIndexerResponseItem represents the OpenSearch response item. -// -type BulkIndexerResponseItem struct { - Index string `json:"_index"` - DocumentID string `json:"_id"` - Version int64 `json:"_version"` - Result string `json:"result"` - Status int `json:"status"` - SeqNo int64 `json:"_seq_no"` - PrimTerm int64 `json:"_primary_term"` - - Shards struct { - Total int `json:"total"` - Successful int `json:"successful"` - Failed int `json:"failed"` - } `json:"_shards"` - - Error struct { - Type string `json:"type"` - Reason string `json:"reason"` - Cause struct { - Type string `json:"type"` - Reason string `json:"reason"` - ScriptStack *[]string `json:"script_stack,omitempty"` - Script *string `json:"script,omitempty"` - Lang *string `json:"lang,omitempty"` - Position *struct { - Offset int `json:"offset"` - Start int `json:"start"` - End int `json:"end"` - } `json:"position,omitempty"` - Cause *struct { - Type string `json:"type"` - Reason string `json:"reason"` - } `json:"caused_by"` - } `json:"caused_by,omitempty"` - } `json:"error,omitempty"` -} - -// BulkResponseJSONDecoder defines the interface for custom JSON decoders. -// -type BulkResponseJSONDecoder interface { - UnmarshalFromReader(io.Reader, *BulkIndexerResponse) error -} - // BulkIndexerDebugLogger defines the interface for a debugging logger. -// type BulkIndexerDebugLogger interface { Printf(string, ...interface{}) } @@ -223,14 +164,13 @@ type bulkIndexerStats struct { } // NewBulkIndexer creates a new bulk indexer. -// func NewBulkIndexer(cfg BulkIndexerConfig) (BulkIndexer, error) { if cfg.Client == nil { - cfg.Client, _ = opensearch.NewDefaultClient() - } - - if cfg.Decoder == nil { - cfg.Decoder = defaultJSONDecoder{} + var err error + cfg.Client, err = opensearchapi.NewDefaultClient() + if err != nil { + return nil, err + } } if cfg.NumWorkers == 0 { @@ -242,7 +182,7 @@ func NewBulkIndexer(cfg BulkIndexerConfig) (BulkIndexer, error) { } if cfg.FlushInterval == 0 { - cfg.FlushInterval = 30 * time.Second + cfg.FlushInterval = defaultFlushInterval } bi := bulkIndexer{ @@ -259,7 +199,6 @@ func NewBulkIndexer(cfg BulkIndexerConfig) (BulkIndexer, error) { // Add adds an item to the indexer. // // Adding an item after a call to Close() will panic. -// func (bi *bulkIndexer) Add(ctx context.Context, item BulkIndexerItem) error { atomic.AddUint64(&bi.stats.numAdded, 1) @@ -277,7 +216,6 @@ func (bi *bulkIndexer) Add(ctx context.Context, item BulkIndexerItem) error { // Close stops the periodic flush, closes the indexer queue channel, // notifies the done channel and calls flush on all writers. -// func (bi *bulkIndexer) Close(ctx context.Context) error { bi.ticker.Stop() close(bi.queue) @@ -301,6 +239,7 @@ func (bi *bulkIndexer) Close(ctx context.Context) error { if bi.config.OnError != nil { bi.config.OnError(ctx, err) } + continue } } @@ -310,7 +249,6 @@ func (bi *bulkIndexer) Close(ctx context.Context) error { } // Stats returns indexer statistics. -// func (bi *bulkIndexer) Stats() BulkIndexerStats { return BulkIndexerStats{ NumAdded: atomic.LoadUint64(&bi.stats.numAdded), @@ -325,7 +263,6 @@ func (bi *bulkIndexer) Stats() BulkIndexerStats { } // init initializes the bulk indexer. -// func (bi *bulkIndexer) init() { bi.queue = make(chan BulkIndexerItem, bi.config.NumWorkers) @@ -335,15 +272,19 @@ func (bi *bulkIndexer) init() { ch: bi.queue, bi: bi, buf: bytes.NewBuffer(make([]byte, 0, bi.config.FlushBytes)), - aux: make([]byte, 0, 512)} + //nolint:gomnd // Predefine the slice capacity + aux: make([]byte, 0, 512), + } w.run() bi.workers = append(bi.workers, &w) } bi.wg.Add(bi.config.NumWorkers) bi.ticker = time.NewTicker(bi.config.FlushInterval) + go func() { ctx := context.Background() + for { select { case <-bi.done: @@ -352,6 +293,7 @@ func (bi *bulkIndexer) init() { if bi.config.DebugLogger != nil { bi.config.DebugLogger.Printf("[indexer] Auto-flushing workers after %s\n", bi.config.FlushInterval) } + for _, w := range bi.workers { w.mu.Lock() if w.buf.Len() > 0 { @@ -360,6 +302,7 @@ func (bi *bulkIndexer) init() { if bi.config.OnError != nil { bi.config.OnError(ctx, err) } + continue } } @@ -371,7 +314,6 @@ func (bi *bulkIndexer) init() { } // worker represents an indexer worker. -// type worker struct { id int ch <-chan BulkIndexerItem @@ -383,7 +325,6 @@ type worker struct { } // run launches the worker in a goroutine. -// func (w *worker) run() { go func() { ctx := context.Background() @@ -402,19 +343,22 @@ func (w *worker) run() { if err := w.writeMeta(item); err != nil { if item.OnFailure != nil { - item.OnFailure(ctx, item, BulkIndexerResponseItem{}, err) + item.OnFailure(ctx, item, opensearchapi.BulkRespItem{}, err) } + atomic.AddUint64(&w.bi.stats.numFailed, 1) w.mu.Unlock() + continue } if err := w.writeBody(&item); err != nil { if item.OnFailure != nil { - item.OnFailure(ctx, item, BulkIndexerResponseItem{}, err) + item.OnFailure(ctx, item, opensearchapi.BulkRespItem{}, err) } atomic.AddUint64(&w.bi.stats.numFailed, 1) w.mu.Unlock() + continue } @@ -422,9 +366,11 @@ func (w *worker) run() { if w.buf.Len() >= w.bi.config.FlushBytes { if err := w.flush(ctx); err != nil { w.mu.Unlock() + if w.bi.config.OnError != nil { w.bi.config.OnError(ctx, err) } + continue } } @@ -434,9 +380,9 @@ func (w *worker) run() { } // writeMeta formats and writes the item metadata to the buffer; it must be called under a lock. -// func (w *worker) writeMeta(item BulkIndexerItem) error { var err error + meta := bulkActionMetadata{ Index: item.Index, DocumentID: item.DocumentID, @@ -450,54 +396,60 @@ func (w *worker) writeMeta(item BulkIndexerItem) error { RequireAlias: item.RequireAlias, RetryOnConflict: item.RetryOnConflict, } + // Can not specify version or seq num if no document ID is passed if meta.DocumentID == "" { meta.Version = nil meta.VersionType = nil } + w.aux, err = json.Marshal(map[string]bulkActionMetadata{ item.Action: meta, }) if err != nil { return err } + _, err = w.buf.Write(w.aux) if err != nil { return err } + w.aux = w.aux[:0] + _, err = w.buf.WriteRune('\n') if err != nil { return err } + return nil } // writeBody writes the item body to the buffer; it must be called under a lock. -// func (w *worker) writeBody(item *BulkIndexerItem) error { - if item.Body != nil { - if _, err := w.buf.ReadFrom(item.Body); err != nil { - if w.bi.config.OnError != nil { - w.bi.config.OnError(context.Background(), err) - } - return err - } + if item.Body == nil { + return nil + } - if _, err := item.Body.Seek(0, io.SeekStart); err != nil { - if w.bi.config.OnError != nil { - w.bi.config.OnError(context.Background(), err) - } - return err + if _, err := w.buf.ReadFrom(item.Body); err != nil { + if w.bi.config.OnError != nil { + w.bi.config.OnError(context.Background(), err) } + return err + } - w.buf.WriteRune('\n') + if _, err := item.Body.Seek(0, io.SeekStart); err != nil { + if w.bi.config.OnError != nil { + w.bi.config.OnError(context.Background(), err) + } + return err } + + w.buf.WriteRune('\n') return nil } // flush writes out the worker buffer; it must be called under a lock. -// func (w *worker) flush(ctx context.Context) error { if w.bi.config.OnFlushStart != nil { ctx = w.bi.config.OnFlushStart(ctx) @@ -516,7 +468,7 @@ func (w *worker) flush(ctx context.Context) error { var ( err error - blk BulkIndexerResponse + blk *opensearchapi.BulkResp ) defer func() { @@ -529,58 +481,39 @@ func (w *worker) flush(ctx context.Context) error { } atomic.AddUint64(&w.bi.stats.numRequests, 1) - req := opensearchapi.BulkRequest{ + req := opensearchapi.BulkReq{ Index: w.bi.config.Index, Body: w.buf, - - Pipeline: w.bi.config.Pipeline, - Refresh: w.bi.config.Refresh, - Routing: w.bi.config.Routing, - Source: w.bi.config.Source, - SourceExcludes: w.bi.config.SourceExcludes, - SourceIncludes: w.bi.config.SourceIncludes, - Timeout: w.bi.config.Timeout, - WaitForActiveShards: w.bi.config.WaitForActiveShards, - - Pretty: w.bi.config.Pretty, - Human: w.bi.config.Human, - ErrorTrace: w.bi.config.ErrorTrace, - FilterPath: w.bi.config.FilterPath, - Header: w.bi.config.Header, + Params: opensearchapi.BulkParams{ + Pipeline: w.bi.config.Pipeline, + Refresh: w.bi.config.Refresh, + Routing: w.bi.config.Routing, + Source: w.bi.config.Source, + SourceExcludes: w.bi.config.SourceExcludes, + SourceIncludes: w.bi.config.SourceIncludes, + Timeout: w.bi.config.Timeout, + WaitForActiveShards: w.bi.config.WaitForActiveShards, + + Pretty: w.bi.config.Pretty, + Human: w.bi.config.Human, + ErrorTrace: w.bi.config.ErrorTrace, + }, + Header: w.bi.config.Header, } - res, err := req.Do(ctx, w.bi.config.Client) + blk, err = w.bi.config.Client.Bulk(ctx, req) if err != nil { atomic.AddUint64(&w.bi.stats.numFailed, uint64(len(w.items))) if w.bi.config.OnError != nil { - w.bi.config.OnError(ctx, fmt.Errorf("flush: %s", err)) + w.bi.config.OnError(ctx, fmt.Errorf("flush: %w", err)) } - return fmt.Errorf("flush: %s", err) - } - if res.Body != nil { - defer res.Body.Close() - } - if res.IsError() { - atomic.AddUint64(&w.bi.stats.numFailed, uint64(len(w.items))) - // TODO(karmi): Wrap error (include response struct) - if w.bi.config.OnError != nil { - w.bi.config.OnError(ctx, fmt.Errorf("flush: %s", err)) - } - return fmt.Errorf("flush: %s", res.String()) - } - - if err := w.bi.config.Decoder.UnmarshalFromReader(res.Body, &blk); err != nil { - // TODO(karmi): Wrap error (include response struct) - if w.bi.config.OnError != nil { - w.bi.config.OnError(ctx, fmt.Errorf("flush: %s", err)) - } - return fmt.Errorf("flush: error parsing response body: %s", err) + return fmt.Errorf("flush: %w", err) } for i, blkItem := range blk.Items { var ( item BulkIndexerItem - info BulkIndexerResponseItem + info opensearchapi.BulkRespItem op string ) @@ -592,7 +525,7 @@ func (w *worker) flush(ctx context.Context) error { op = k info = v } - if info.Error.Type != "" || info.Status > 201 { + if info.Error != nil || info.Status > 201 { atomic.AddUint64(&w.bi.stats.numFailed, 1) if item.OnFailure != nil { item.OnFailure(ctx, item, info, nil) @@ -619,9 +552,3 @@ func (w *worker) flush(ctx context.Context) error { return err } - -type defaultJSONDecoder struct{} - -func (d defaultJSONDecoder) UnmarshalFromReader(r io.Reader, blk *BulkIndexerResponse) error { - return json.NewDecoder(r).Decode(blk) -} diff --git a/opensearchutil/bulk_indexer_benchmark_test.go b/opensearchutil/bulk_indexer_benchmark_test.go index a2dcd56b1..28ea58881 100644 --- a/opensearchutil/bulk_indexer_benchmark_test.go +++ b/opensearchutil/bulk_indexer_benchmark_test.go @@ -24,20 +24,21 @@ // specific language governing permissions and limitations // under the License. -// +build !integration +//go:build !integration package opensearchutil_test import ( "bytes" "context" - "io/ioutil" + "io" "net/http" "strconv" "strings" "testing" "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" "github.com/opensearch-project/opensearch-go/v2/opensearchutil" ) @@ -62,8 +63,8 @@ var mockResponseBody = `{ type mockTransp struct{} -func (t *mockTransp) RoundTrip(req *http.Request) (*http.Response, error) { - return &http.Response{Body: ioutil.NopCloser(strings.NewReader(mockResponseBody))}, nil // 1x alloc +func (t *mockTransp) RoundTrip(_ *http.Request) (*http.Response, error) { + return &http.Response{Body: io.NopCloser(strings.NewReader(mockResponseBody))}, nil // 1x alloc } func BenchmarkBulkIndexer(b *testing.B) { @@ -72,7 +73,7 @@ func BenchmarkBulkIndexer(b *testing.B) { b.Run("Basic", func(b *testing.B) { b.ResetTimer() - client, _ := opensearch.NewClient(opensearch.Config{Transport: &mockTransp{}}) + client, _ := opensearchapi.NewClient(opensearchapi.Config{Client: opensearch.Config{Transport: &mockTransp{}}}) bi, _ := opensearchutil.NewBulkIndexer(opensearchutil.BulkIndexerConfig{ Client: client, FlushBytes: 1024, diff --git a/opensearchutil/bulk_indexer_example_test.go b/opensearchutil/bulk_indexer_example_test.go index f519f37d5..a77e1723a 100644 --- a/opensearchutil/bulk_indexer_example_test.go +++ b/opensearchutil/bulk_indexer_example_test.go @@ -24,7 +24,7 @@ // specific language governing permissions and limitations // under the License. -// +build !integration +//go:build !integration package opensearchutil_test @@ -36,6 +36,7 @@ import ( "time" "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" "github.com/opensearch-project/opensearch-go/v2/opensearchutil" ) @@ -44,18 +45,20 @@ func ExampleNewBulkIndexer() { // Create the OpenSearch client // - client, err := opensearch.NewClient(opensearch.Config{ - // Retry on 429 TooManyRequests statuses - // - RetryOnStatus: []int{502, 503, 504, 429}, - - // A simple incremental backoff function - // - RetryBackoff: func(i int) time.Duration { return time.Duration(i) * 100 * time.Millisecond }, - - // Retry up to 5 attempts - // - MaxRetries: 5, + client, err := opensearchapi.NewClient(opensearchapi.Config{ + Client: opensearch.Config{ + // Retry on 429 TooManyRequests statuses + // + RetryOnStatus: []int{502, 503, 504, 429}, + + // A simple incremental backoff function + // + RetryBackoff: func(i int) time.Duration { return time.Duration(i) * 100 * time.Millisecond }, + + // Retry up to 5 attempts + // + MaxRetries: 5, + }, }) if err != nil { log.Fatalf("Error creating the client: %s", err) @@ -91,7 +94,7 @@ func ExampleNewBulkIndexer() { OnSuccess: func( ctx context.Context, item opensearchutil.BulkIndexerItem, - res opensearchutil.BulkIndexerResponseItem, + res opensearchapi.BulkRespItem, ) { fmt.Printf("[%d] %s test/%s", res.Status, res.Result, item.DocumentID) }, @@ -100,7 +103,7 @@ func ExampleNewBulkIndexer() { OnFailure: func( ctx context.Context, item opensearchutil.BulkIndexerItem, - res opensearchutil.BulkIndexerResponseItem, err error, + res opensearchapi.BulkRespItem, err error, ) { if err != nil { log.Printf("ERROR: %s", err) @@ -125,9 +128,8 @@ func ExampleNewBulkIndexer() { stats := indexer.Stats() if stats.NumFailed > 0 { log.Fatalf("Indexed [%d] documents with [%d] errors", stats.NumFlushed, stats.NumFailed) - } else { - log.Printf("Successfully indexed [%d] documents", stats.NumFlushed) } + log.Printf("Successfully indexed [%d] documents", stats.NumFlushed) // For optimal performance, consider using a third-party package for JSON decoding and HTTP transport. } diff --git a/opensearchutil/bulk_indexer_integration_test.go b/opensearchutil/bulk_indexer_integration_test.go index a07677af4..9e3e8ed6d 100644 --- a/opensearchutil/bulk_indexer_integration_test.go +++ b/opensearchutil/bulk_indexer_integration_test.go @@ -25,7 +25,6 @@ // under the License. //go:build integration -// +build integration package opensearchutil_test @@ -39,12 +38,14 @@ import ( "time" "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" "github.com/opensearch-project/opensearch-go/v2/opensearchtransport" "github.com/opensearch-project/opensearch-go/v2/opensearchutil" ) func TestBulkIndexerIntegration(t *testing.T) { testRecordCount := uint64(10000) + ctx := context.Background() testCases := []struct { name string @@ -155,16 +156,24 @@ func TestBulkIndexerIntegration(t *testing.T) { for _, c := range testCases { indexName := "test-bulk-integration" - client, _ := opensearch.NewClient(opensearch.Config{ - CompressRequestBody: c.compressRequestBodyEnabled, - Logger: &opensearchtransport.ColorLogger{Output: os.Stdout}, - }) + client, _ := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + CompressRequestBody: c.compressRequestBodyEnabled, + Logger: &opensearchtransport.ColorLogger{Output: os.Stdout}, + }, + }, + ) - client.Indices.Delete([]string{indexName}, client.Indices.Delete.WithIgnoreUnavailable(true)) + client.Indices.Delete(ctx, opensearchapi.IndicesDeleteReq{Indices: []string{indexName}, Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}}) client.Indices.Create( - indexName, - client.Indices.Create.WithBody(strings.NewReader(`{"settings": {"number_of_shards": 1, "number_of_replicas": 0, "refresh_interval":"5s"}}`)), - client.Indices.Create.WithWaitForActiveShards("1")) + ctx, + opensearchapi.IndicesCreateReq{ + Index: indexName, + Body: strings.NewReader(`{"settings": {"number_of_shards": 1, "number_of_replicas": 0, "refresh_interval":"5s"}}`), + Params: opensearchapi.IndicesCreateParams{WaitForActiveShards: "1"}, + }, + ) for _, tt := range c.tests { t.Run(tt.name, func(t *testing.T) { @@ -279,7 +288,7 @@ func TestBulkIndexerIntegration(t *testing.T) { t.Errorf("Unexpected NumIndexed: want=%d, got=%d", expectedIndexed, stats.NumIndexed) } - res, err := client.Indices.Exists([]string{"test-index-a", "test-index-b", "test-index-c"}) + res, err := client.Indices.Exists(ctx, opensearchapi.IndicesExistsReq{Indices: []string{"test-index-a", "test-index-b", "test-index-c"}}) if err != nil { t.Fatalf("Unexpected error: %s", err) } diff --git a/opensearchutil/bulk_indexer_internal_test.go b/opensearchutil/bulk_indexer_internal_test.go index 705f7d22d..1707e14b6 100644 --- a/opensearchutil/bulk_indexer_internal_test.go +++ b/opensearchutil/bulk_indexer_internal_test.go @@ -25,17 +25,14 @@ // under the License. //go:build !integration -// +build !integration package opensearchutil import ( "bytes" "context" - "encoding/json" "fmt" "io" - "io/ioutil" "log" "net/http" "os" @@ -48,6 +45,7 @@ import ( "time" "github.com/opensearch-project/opensearch-go/v2" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" "github.com/opensearch-project/opensearch-go/v2/opensearchtransport" ) @@ -59,7 +57,7 @@ var infoBody = `{ }` var defaultRoundTripFunc = func(*http.Request) (*http.Response, error) { - return &http.Response{Body: ioutil.NopCloser(strings.NewReader(`{}`))}, nil + return &http.Response{Body: io.NopCloser(strings.NewReader(`{}`))}, nil } type mockTransport struct { @@ -83,10 +81,13 @@ func TestBulkIndexer(t *testing.T) { numItems = 6 ) - client, _ := opensearch.NewClient(opensearch.Config{Transport: &mockTransport{ + client, _ := opensearchapi.NewClient(opensearchapi.Config{Client: opensearch.Config{Transport: &mockTransport{ RoundTripFunc: func(request *http.Request) (*http.Response, error) { if request.URL.Path == "/" { - return &http.Response{Header: http.Header{"Content-Type": []string{"application/json"}}, Body: ioutil.NopCloser(strings.NewReader(infoBody))}, nil + return &http.Response{ + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(infoBody)), + }, nil } countReqs++ @@ -98,16 +99,17 @@ func TestBulkIndexer(t *testing.T) { case 3: testfile = "testdata/bulk_response_1c.json" } - bodyContent, _ := ioutil.ReadFile(testfile) - return &http.Response{Body: ioutil.NopCloser(bytes.NewBuffer(bodyContent))}, nil + bodyContent, _ := os.ReadFile(testfile) + return &http.Response{Body: io.NopCloser(bytes.NewBuffer(bodyContent))}, nil }, - }}) + }}}) cfg := BulkIndexerConfig{ NumWorkers: 1, FlushBytes: 50, FlushInterval: time.Hour, // Disable auto-flushing, because response doesn't match number of items - Client: client} + Client: client, + } if os.Getenv("DEBUG") != "" { cfg.DebugLogger = log.New(os.Stdout, "", 0) } @@ -178,7 +180,7 @@ func TestBulkIndexer(t *testing.T) { }) t.Run("Add() Timeout", func(t *testing.T) { - client, _ := opensearch.NewClient(opensearch.Config{Transport: &mockTransport{}}) + client, _ := opensearchapi.NewClient(opensearchapi.Config{Client: opensearch.Config{Transport: &mockTransport{}}}) bi, _ := NewBulkIndexer(BulkIndexerConfig{NumWorkers: 1, Client: client}) ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) defer cancel() @@ -204,7 +206,7 @@ func TestBulkIndexer(t *testing.T) { }) t.Run("Close() Cancel", func(t *testing.T) { - client, _ := opensearch.NewClient(opensearch.Config{Transport: &mockTransport{}}) + client, _ := opensearchapi.NewClient(opensearchapi.Config{Client: opensearch.Config{Transport: &mockTransport{}}}) bi, _ := NewBulkIndexer(BulkIndexerConfig{ NumWorkers: 1, FlushBytes: 1, @@ -218,31 +220,33 @@ func TestBulkIndexer(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() if err := bi.Close(ctx); err == nil { - t.Errorf("Expected context cancelled error, but got: %v", err) + t.Errorf("Expected context canceled error, but got: %v", err) } }) t.Run("Indexer Callback", func(t *testing.T) { - config := opensearch.Config{ - Transport: &mockTransport{ - RoundTripFunc: func(request *http.Request) (*http.Response, error) { - if request.URL.Path == "/" { - return &http.Response{Body: ioutil.NopCloser(strings.NewReader(infoBody))}, nil - } - - return nil, fmt.Errorf("Mock transport error") + config := opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &mockTransport{ + RoundTripFunc: func(request *http.Request) (*http.Response, error) { + if request.URL.Path == "/" { + return &http.Response{Body: io.NopCloser(strings.NewReader(infoBody))}, nil + } + + return nil, fmt.Errorf("Mock transport error") + }, }, }, } if os.Getenv("DEBUG") != "" { - config.Logger = &opensearchtransport.ColorLogger{ + config.Client.Logger = &opensearchtransport.ColorLogger{ Output: os.Stdout, EnableRequestBody: true, EnableResponseBody: true, } } - client, _ := opensearch.NewClient(config) + client, _ := opensearchapi.NewClient(config) var indexerError error biCfg := BulkIndexerConfig{ @@ -279,23 +283,29 @@ func TestBulkIndexer(t *testing.T) { numItems = 4 numFailed = 2 - bodyContent, _ = ioutil.ReadFile("testdata/bulk_response_2.json") + bodyContent, _ = os.ReadFile("testdata/bulk_response_2.json") ) - client, _ := opensearch.NewClient(opensearch.Config{Transport: &mockTransport{ - RoundTripFunc: func(request *http.Request) (*http.Response, error) { - if request.URL.Path == "/" { - return &http.Response{ - StatusCode: http.StatusOK, - Status: "200 OK", - Body: ioutil.NopCloser(strings.NewReader(infoBody)), - Header: http.Header{"Content-Type": []string{"application/json"}}, - }, nil - } - - return &http.Response{Body: ioutil.NopCloser(bytes.NewBuffer(bodyContent))}, nil + client, _ := opensearchapi.NewClient( + opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &mockTransport{ + RoundTripFunc: func(request *http.Request) (*http.Response, error) { + if request.URL.Path == "/" { + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Body: io.NopCloser(strings.NewReader(infoBody)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + }, nil + } + + return &http.Response{Body: io.NopCloser(bytes.NewBuffer(bodyContent))}, nil + }, + }, + }, }, - }}) + ) cfg := BulkIndexerConfig{NumWorkers: 1, Client: client} if os.Getenv("DEBUG") != "" { @@ -304,23 +314,23 @@ func TestBulkIndexer(t *testing.T) { bi, _ := NewBulkIndexer(cfg) - successFunc := func(ctx context.Context, item BulkIndexerItem, res BulkIndexerResponseItem) { + successFunc := func(ctx context.Context, item BulkIndexerItem, res opensearchapi.BulkRespItem) { atomic.AddUint64(&countSuccessful, 1) - buf, err := ioutil.ReadAll(item.Body) + buf, err := io.ReadAll(item.Body) if err != nil { t.Fatalf("Unexpected error: %s", err) } successfulItemBodies = append(successfulItemBodies, string(buf)) } - failureFunc := func(ctx context.Context, item BulkIndexerItem, res BulkIndexerResponseItem, err error) { + failureFunc := func(ctx context.Context, item BulkIndexerItem, res opensearchapi.BulkRespItem, err error) { if err != nil { t.Fatalf("Unexpected error: %s", err) } atomic.AddUint64(&countFailed, 1) failedIDs = append(failedIDs, item.DocumentID) - buf, err := ioutil.ReadAll(item.Body) + buf, err := io.ReadAll(item.Body) if err != nil { t.Fatalf("Unexpected error: %s", err) } @@ -421,7 +431,7 @@ func TestBulkIndexer(t *testing.T) { t.Run("OnFlush callbacks", func(t *testing.T) { type contextKey string - client, _ := opensearch.NewClient(opensearch.Config{Transport: &mockTransport{}}) + client, _ := opensearchapi.NewClient(opensearchapi.Config{Client: opensearch.Config{Transport: &mockTransport{}}}) bi, _ := NewBulkIndexer(BulkIndexerConfig{ Client: client, Index: "foo", @@ -458,23 +468,25 @@ func TestBulkIndexer(t *testing.T) { }) t.Run("Automatic flush", func(t *testing.T) { - client, _ := opensearch.NewClient(opensearch.Config{Transport: &mockTransport{ + client, _ := opensearchapi.NewClient(opensearchapi.Config{Client: opensearch.Config{Transport: &mockTransport{ RoundTripFunc: func(request *http.Request) (*http.Response, error) { if request.URL.Path == "/" { return &http.Response{ StatusCode: http.StatusOK, Status: "200 OK", - Body: ioutil.NopCloser(strings.NewReader(infoBody)), + Body: io.NopCloser(strings.NewReader(infoBody)), Header: http.Header{"Content-Type": []string{"application/json"}}, }, nil } return &http.Response{ - StatusCode: http.StatusOK, - Status: "200 OK", - Body: ioutil.NopCloser(strings.NewReader(`{"items":[{"index": {}}]}`))}, nil + StatusCode: http.StatusOK, + Status: "200 OK", + Body: io.NopCloser(strings.NewReader(`{"items":[{"index": {}}]}`)), + }, + nil }, - }}) + }}}) cfg := BulkIndexerConfig{ NumWorkers: 1, @@ -525,47 +537,51 @@ func TestBulkIndexer(t *testing.T) { numItems = 2 ) - cfg := opensearch.Config{ - Transport: &mockTransport{ - RoundTripFunc: func(request *http.Request) (*http.Response, error) { - if request.URL.Path == "/" { + cfg := opensearchapi.Config{ + Client: opensearch.Config{ + Transport: &mockTransport{ + RoundTripFunc: func(request *http.Request) (*http.Response, error) { + if request.URL.Path == "/" { + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Body: io.NopCloser(strings.NewReader(infoBody)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + }, nil + } + + countReqs++ + if countReqs <= 4 { + return &http.Response{ + StatusCode: http.StatusTooManyRequests, + Status: "429 TooManyRequests", + Body: io.NopCloser(strings.NewReader(`{"took":1}`)), + }, + nil + } + bodyContent, _ := os.ReadFile("testdata/bulk_response_1c.json") return &http.Response{ StatusCode: http.StatusOK, Status: "200 OK", - Body: ioutil.NopCloser(strings.NewReader(infoBody)), - Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(bytes.NewBuffer(bodyContent)), }, nil - } + }, + }, - countReqs++ - if countReqs <= 4 { - return &http.Response{ - StatusCode: http.StatusTooManyRequests, - Status: "429 TooManyRequests", - Body: ioutil.NopCloser(strings.NewReader(`{"took":1}`))}, nil + MaxRetries: 5, + RetryOnStatus: []int{502, 503, 504, 429}, + RetryBackoff: func(i int) time.Duration { + if os.Getenv("DEBUG") != "" { + fmt.Printf("*** Retry #%d\n", i) } - bodyContent, _ := ioutil.ReadFile("testdata/bulk_response_1c.json") - return &http.Response{ - StatusCode: http.StatusOK, - Status: "200 OK", - Body: ioutil.NopCloser(bytes.NewBuffer(bodyContent)), - }, nil + return time.Duration(i) * 100 * time.Millisecond }, }, - - MaxRetries: 5, - RetryOnStatus: []int{502, 503, 504, 429}, - RetryBackoff: func(i int) time.Duration { - if os.Getenv("DEBUG") != "" { - fmt.Printf("*** Retry #%d\n", i) - } - return time.Duration(i) * 100 * time.Millisecond - }, } if os.Getenv("DEBUG") != "" { - cfg.Logger = &opensearchtransport.ColorLogger{Output: os.Stdout} + cfg.Client.Logger = &opensearchtransport.ColorLogger{Output: os.Stdout} } - client, _ := opensearch.NewClient(cfg) + client, _ := opensearchapi.NewClient(cfg) biCfg := BulkIndexerConfig{NumWorkers: 1, FlushBytes: 50, Client: client} if os.Getenv("DEBUG") != "" { @@ -576,7 +592,7 @@ func TestBulkIndexer(t *testing.T) { for i := 1; i <= numItems; i++ { wg.Add(1) - go func(i int) { + go func() { defer wg.Done() err := bi.Add(context.Background(), BulkIndexerItem{ Action: "foo", @@ -586,7 +602,7 @@ func TestBulkIndexer(t *testing.T) { t.Errorf("Unexpected error: %s", err) return } - }(i) + }() } wg.Wait() @@ -614,30 +630,6 @@ func TestBulkIndexer(t *testing.T) { } }) - t.Run("Custom JSON Decoder", func(t *testing.T) { - client, _ := opensearch.NewClient(opensearch.Config{Transport: &mockTransport{}}) - bi, _ := NewBulkIndexer(BulkIndexerConfig{Client: client, Decoder: customJSONDecoder{}}) - - err := bi.Add(context.Background(), BulkIndexerItem{ - Action: "index", - DocumentID: "1", - Body: strings.NewReader(`{"title":"foo"}`), - }) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - - if err := bi.Close(context.Background()); err != nil { - t.Errorf("Unexpected error: %s", err) - } - - stats := bi.Stats() - - if stats.NumAdded != uint64(1) { - t.Errorf("Unexpected NumAdded: %d", stats.NumAdded) - } - }) - t.Run("Worker.writeMeta()", func(t *testing.T) { type args struct { item BulkIndexerItem @@ -770,18 +762,11 @@ func TestBulkIndexer(t *testing.T) { if w.buf.String() != tt.want { t.Errorf("worker.writeMeta() %s = got [%s], want [%s]", tt.name, w.buf.String(), tt.want) } - }) } }) } -type customJSONDecoder struct{} - -func (d customJSONDecoder) UnmarshalFromReader(r io.Reader, blk *BulkIndexerResponse) error { - return json.NewDecoder(r).Decode(blk) -} - func strPointer(s string) *string { return &s } diff --git a/opensearchutil/doc.go b/opensearchutil/doc.go index 02fb55c66..1ec33942c 100644 --- a/opensearchutil/doc.go +++ b/opensearchutil/doc.go @@ -26,6 +26,5 @@ /* Package opensearchutil provides helper utilities to the Go client for OpenSearch. - */ package opensearchutil diff --git a/opensearchutil/json_reader.go b/opensearchutil/json_reader.go index aa9ff490b..cd34a1f8b 100644 --- a/opensearchutil/json_reader.go +++ b/opensearchutil/json_reader.go @@ -33,20 +33,17 @@ import ( ) // NewJSONReader encodes v into JSON and returns it as an io.Reader. -// func NewJSONReader(v interface{}) io.Reader { return &JSONReader{val: v, buf: nil} } // JSONEncoder defines the interface for custom JSON encoders. -// type JSONEncoder interface { EncodeJSON(io.Writer) error } // JSONReader represents a reader which takes an interface value, // encodes it into JSON, and wraps it in an io.Reader. -// type JSONReader struct { val interface{} buf interface { @@ -56,7 +53,6 @@ type JSONReader struct { } // Read implements the io.Reader interface. -// func (r *JSONReader) Read(p []byte) (int, error) { if r.buf == nil { r.buf = new(bytes.Buffer) @@ -69,7 +65,6 @@ func (r *JSONReader) Read(p []byte) (int, error) { } // WriteTo implements the io.WriterTo interface. -// func (r *JSONReader) WriteTo(w io.Writer) (int64, error) { cw := countingWriter{Writer: w} err := r.encode(&cw) diff --git a/opensearchutil/json_reader_benchmark_test.go b/opensearchutil/json_reader_benchmark_test.go index 24c489ebe..d3a00f05a 100644 --- a/opensearchutil/json_reader_benchmark_test.go +++ b/opensearchutil/json_reader_benchmark_test.go @@ -24,7 +24,7 @@ // specific language governing permissions and limitations // under the License. -// +build !integration +//go:build !integration package opensearchutil_test @@ -33,7 +33,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "strings" "testing" @@ -48,12 +47,13 @@ type Foo struct { func (f Foo) EncodeJSON(w io.Writer) error { var b bytes.Buffer + b.WriteString(`{"bar":"`) b.WriteString(strings.ToUpper(f.Bar)) b.WriteString(`"}`) b.WriteString("\n") - _, err := b.WriteTo(w) - if err != nil { + + if _, err := b.WriteTo(w); err != nil { return err } return nil @@ -68,7 +68,7 @@ func BenchmarkJSONReader(b *testing.B) { var buf bytes.Buffer for i := 0; i < b.N; i++ { json.NewEncoder(&buf).Encode(map[string]string{"foo": "bar"}) - if string(buf.String()) != `{"foo":"bar"}`+"\n" { + if buf.String() != `{"foo":"bar"}`+"\n" { b.Fatalf("Unexpected output: %q", buf.String()) } buf.Reset() @@ -79,7 +79,7 @@ func BenchmarkJSONReader(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - out, _ := ioutil.ReadAll(opensearchutil.NewJSONReader(map[string]string{"foo": "bar"})) + out, _ := io.ReadAll(opensearchutil.NewJSONReader(map[string]string{"foo": "bar"})) if string(out) != `{"foo":"bar"}`+"\n" { b.Fatalf("Unexpected output: %q", out) } @@ -103,7 +103,7 @@ func BenchmarkJSONReader(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - out, _ := ioutil.ReadAll(opensearchutil.NewJSONReader(Foo{Bar: "baz"})) + out, _ := io.ReadAll(opensearchutil.NewJSONReader(Foo{Bar: "baz"})) if string(out) != `{"bar":"BAZ"}`+"\n" { b.Fatalf("Unexpected output: %q", out) } diff --git a/opensearchutil/json_reader_integration_test.go b/opensearchutil/json_reader_integration_test.go index 3e871334e..9e1c67ec0 100644 --- a/opensearchutil/json_reader_integration_test.go +++ b/opensearchutil/json_reader_integration_test.go @@ -25,42 +25,40 @@ // under the License. //go:build integration -// +build integration package opensearchutil_test import ( + "context" + "fmt" "strings" "testing" - "github.com/opensearch-project/opensearch-go/v2" + "golang.org/x/exp/slices" + "github.com/opensearch-project/opensearch-go/v2/opensearchapi" "github.com/opensearch-project/opensearch-go/v2/opensearchutil" ) func TestJSONReaderIntegration(t *testing.T) { t.Run("Index and search", func(t *testing.T) { - var ( - res *opensearchapi.Response - err error - ) + ctx := context.Background() - client, err := opensearch.NewDefaultClient() + client, err := opensearchapi.NewDefaultClient() if err != nil { t.Fatalf("Error creating the client: %s\n", err) } - client.Indices.Delete([]string{"test"}, client.Indices.Delete.WithIgnoreUnavailable(true)) + client.Indices.Delete(ctx, opensearchapi.IndicesDeleteReq{Indices: []string{"test"}, Params: opensearchapi.IndicesDeleteParams{IgnoreUnavailable: opensearchapi.ToPointer(true)}}) doc := struct { Title string `json:"title"` }{Title: "Foo Bar"} - res, err = client.Index("test", opensearchutil.NewJSONReader(&doc), client.Index.WithRefresh("true")) + _, err = client.Index(ctx, opensearchapi.IndexReq{Index: "test", Body: opensearchutil.NewJSONReader(&doc), Params: opensearchapi.IndexParams{Refresh: "true"}}) if err != nil { t.Fatalf("Error getting response: %s", err) } - defer res.Body.Close() query := map[string]interface{}{ "query": map[string]interface{}{ @@ -69,19 +67,16 @@ func TestJSONReaderIntegration(t *testing.T) { }, }, } - - res, err = client.Search( - client.Search.WithIndex("test"), - client.Search.WithBody(opensearchutil.NewJSONReader(&query)), - client.Search.WithPretty(), - ) + req := &opensearchapi.SearchReq{ + Indices: []string{"test"}, + Body: opensearchutil.NewJSONReader(&query), + } + res, err := client.Search(ctx, req) if err != nil { t.Fatalf("Error getting response: %s", err) } - defer res.Body.Close() - - if !strings.Contains(res.String(), "Foo Bar") { - t.Errorf("Unexpected response: %s", res) + if len(res.Hits.Hits) == 0 && !slices.ContainsFunc(res.Hits.Hits, func(c opensearchapi.SearchHit) bool { return strings.Contains(fmt.Sprintf("%v", c.Source), "Foo Bar") }) { + t.Errorf("Unexpected response: %v", res) } }) } diff --git a/opensearchutil/json_reader_internal_test.go b/opensearchutil/json_reader_internal_test.go index ce8e71c1a..7c0985d06 100644 --- a/opensearchutil/json_reader_internal_test.go +++ b/opensearchutil/json_reader_internal_test.go @@ -24,7 +24,7 @@ // specific language governing permissions and limitations // under the License. -// +build !integration +//go:build !integration package opensearchutil @@ -32,16 +32,15 @@ import ( "bytes" "errors" "io" - "io/ioutil" "strings" "testing" ) type errReader struct{} -func (errReader) Read(p []byte) (int, error) { return 1, errors.New("MOCK ERROR") } -func (errReader) Write(p []byte) (int, error) { return 0, errors.New("MOCK ERROR") } -func (errReader) WriteTo(w io.Writer) (int64, error) { return 0, errors.New("MOCK ERROR") } +func (errReader) Read(_ []byte) (int, error) { return 1, errors.New("MOCK ERROR") } +func (errReader) Write(_ []byte) (int, error) { return 0, errors.New("MOCK ERROR") } +func (errReader) WriteTo(_ io.Writer) (int64, error) { return 0, errors.New("MOCK ERROR") } type Foo struct { Bar string @@ -57,14 +56,14 @@ func (f Foo) EncodeJSON(w io.Writer) error { func TestJSONReader(t *testing.T) { t.Run("Default", func(t *testing.T) { - out, _ := ioutil.ReadAll(NewJSONReader(map[string]string{"foo": "bar"})) + out, _ := io.ReadAll(NewJSONReader(map[string]string{"foo": "bar"})) if string(out) != `{"foo":"bar"}`+"\n" { t.Fatalf("Unexpected output: %s", out) } }) t.Run("Custom", func(t *testing.T) { - out, _ := ioutil.ReadAll(NewJSONReader(Foo{Bar: "baz"})) + out, _ := io.ReadAll(NewJSONReader(Foo{Bar: "baz"})) if string(out) != `{"bar":"BAZ"}`+"\n" { t.Fatalf("Unexpected output: %s", out) } diff --git a/request.go b/request.go new file mode 100644 index 000000000..1e2dc4af6 --- /dev/null +++ b/request.go @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package opensearch + +import ( + "net/http" +) + +// Request represents a requests the client can execute +type Request interface { + GetRequest() (*http.Request, error) +} diff --git a/request_builder.go b/request_builder.go new file mode 100644 index 000000000..ebfc1b80d --- /dev/null +++ b/request_builder.go @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package opensearch + +import ( + "io" + "net/http" +) + +const ( + headerContentType = "Content-Type" +) + +// BuildRequest is a helper function to build a http.Request +func BuildRequest(method string, path string, body io.Reader, params map[string]string, headers http.Header) (*http.Request, error) { + //nolint:noctx // ctx gets appended when the requests gets executet + httpReq, err := http.NewRequest(method, path, body) + if err != nil { + return nil, err + } + + if len(params) > 0 { + q := httpReq.URL.Query() + for k, v := range params { + q.Set(k, v) + } + + httpReq.URL.RawQuery = q.Encode() + } + + if body != nil { + httpReq.Header[headerContentType] = []string{"application/json"} + } + + if len(headers) > 0 { + if len(httpReq.Header) == 0 { + httpReq.Header = headers + } else { + for k, vv := range headers { + for _, v := range vv { + httpReq.Header.Add(k, v) + } + } + } + } + return httpReq, nil +} diff --git a/response.go b/response.go new file mode 100644 index 000000000..db4d0191d --- /dev/null +++ b/response.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package opensearch + +import ( + "fmt" + "io" + "net/http" +) + +const httpStatusCodeThreshold = 299 + +// Response represents the API response. +type Response struct { + StatusCode int + Header http.Header + Body io.ReadCloser +} + +// String returns the response as a string. +func (r Response) String() string { + if r.Body != nil { + body, err := io.ReadAll(r.Body) + if err != nil { + body = []byte(fmt.Sprintf("", err)) + } + return fmt.Sprintf("%s %s", r.Status(), body) + } + return r.Status() +} + +// Status retuens the response status as string. +func (r Response) Status() string { + status := http.StatusText(r.StatusCode) + if status == "" { + status = "" + } + return fmt.Sprintf("[%d %s]", r.StatusCode, status) +} + +// IsError returns true when the response status indicates failure. +func (r *Response) IsError() bool { + return r.StatusCode > httpStatusCodeThreshold +} diff --git a/response_test.go b/response_test.go new file mode 100644 index 000000000..0e5e81949 --- /dev/null +++ b/response_test.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The OpenSearch Contributors require contributions made to +// this file be licensed under the Apache-2.0 license or a +// compatible open source license. +// +// Modifications Copyright OpenSearch Contributors. See +// GitHub history for details. + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package opensearch_test + +import ( + "errors" + "io" + "net/http" + "strings" + "testing" + "testing/iotest" + + "github.com/stretchr/testify/assert" + + "github.com/opensearch-project/opensearch-go/v2" +) + +func TestResponse(t *testing.T) { + t.Run("empty response", func(t *testing.T) { + resp := opensearch.Response{} + assert.Equal(t, "[0 ]", resp.Status()) + assert.Equal(t, "[0 ]", resp.String()) + }) + + t.Run("with StatusCode", func(t *testing.T) { + resp := opensearch.Response{StatusCode: http.StatusOK} + assert.Equal(t, "[200 OK]", resp.Status()) + assert.Equal(t, "[200 OK]", resp.String()) + }) + + t.Run("with StatusCode and Body", func(t *testing.T) { + resp := opensearch.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("{\"test\": true}"))} + assert.Equal(t, "[200 OK]", resp.Status()) + assert.Equal(t, "[200 OK] {\"test\": true}", resp.String()) + }) + + t.Run("with StatusCode and failing Body", func(t *testing.T) { + resp := opensearch.Response{StatusCode: http.StatusOK, Body: io.NopCloser(iotest.ErrReader(errors.New("io reader test")))} + assert.Equal(t, "[200 OK]", resp.Status()) + assert.Equal(t, "[200 OK] ", resp.String()) + }) +} diff --git a/signer/aws/aws.go b/signer/aws/aws.go index a812d29fc..05c3fe840 100644 --- a/signer/aws/aws.go +++ b/signer/aws/aws.go @@ -30,6 +30,7 @@ const OpenSearchService = "es" // OpenSearchServerless Amazon OpenSearch Serverless Name const OpenSearchServerless = "aoss" +//nolint:gosec // static empty Body const emptyBodySHA256 = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" // Signer is an interface that will implement opensearchtransport.Signer diff --git a/signer/awsv2/sdkv2signer.go b/signer/awsv2/sdkv2signer.go index aca4fdabd..aeb00711c 100644 --- a/signer/awsv2/sdkv2signer.go +++ b/signer/awsv2/sdkv2signer.go @@ -29,6 +29,7 @@ import ( const ( openSearchService = "es" + //nolint:gosec // static empty Body emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` ) @@ -56,6 +57,7 @@ func NewSignerWithService(cfg aws.Config, service string) (signer.Signer, error) }, nil } +// SignRequest adds headers to the request func (s *awsSdkV2Signer) SignRequest(r *http.Request) error { ctx := context.Background() t := time.Now()